Configure Boto3 to conditionally not execute commands

Viewed 333

I'm building a collection of scripts in Boto3 and I'd like to have a DRY_RUN option where when set to True would not execute the Boto3 commands. I'd like to do this dry run first so I can review the logs first before running the script live.

I know the EC2 client has a DryRun parameter you can pass in, but that raises an error which I don't want. Also my script deals with the Cloudformation client heavily too which doesn't have the DryRun option.

I started by prepending all my Boto3 commands with if not DRY_RUN: ec2_client... but that isn't the most elegant solution. I also thought about passing each Boto3 command as a parameter to a utility function that uses eval() to execute the function if DRY_RUN is False, but that isn't ideal either.

Is there a Boto3 config setting, middleware, mock/stub library, or some python metaprogramming technique that might help here?

1 Answers

I did something like this just for testing:

def create_snapshot(resource, volume_id):
  volume = resource.Volume(volume_id)
  try:
      snap = volume.create_snapshot(
          DryRun=True
      )
  except ClientError as ce:
      print(ce)
      pass
  except Exception as e:
      print(e)
      raise

This way you'll see if the call would succeed, but it won't interrupt your script.

Related