1

I'm working with Boto3 for AWS for my current project. I need to have a few different describe_images arguments for EC2 as optional and I can't use wildcard or empty inputs to get around having them in or not. I'm looking for a way for add arguments being passed as needed rather than having to do a number of if checks with slightly different content.

For example, take the snippet below. I'd like for the Owners and ImageIds arguments to be dynamically added if they are provided upstream but not include them if they aren't. I haven't had any luck with Google yet so figured I would ask make a quick post.

response = ec2.describe_images(
    ExecutableUsers=['all'],
    Filters=search_filters,
    Owners=['309956199498'],
    ImageIds=['ami-26ebbc5c']
)

Thanks

amcelwee
  • 1,175
  • 1
  • 9
  • 10
omnivir
  • 77
  • 6

1 Answers1

2

If you look at the signature of describe_images, you'll see that it accepts the arguments in the form of keyword args (commonly referred to as kwargs). With that signature and a bit of reading on expansion of iterables, you can dynamically build up the keyword args that you want to pass to the describe_images call.

Here's a very simple example below of a function with the same signature that just echoes the keyword args it gets to give you insight into what the function call is actually receiving.

def foo(**kwargs):
     print(kwargs)

owners = None
image_ids = None
search_filters=['a', 'b']

describe_kwargs = {'ExecutableUsers':['all'], 'Filters':search_filters}
foo(**describe_kwargs)

# Now include image ids
describe_kwargs['ImageIds'] = ['ami-26ebbc5c']
foo(**describe_kwargs)

# Now include owners
describe_kwargs['Owners'] = ['309956199498']
foo(**describe_kwargs)

If you run this snippet, you'll see the following:

{'ExecutableUsers': ['all'], 'Filters': ['a', 'b']}
{'ExecutableUsers': ['all'], 'Filters': ['a', 'b'], 'ImageIds': ['ami-26ebbc5c']}
{'ExecutableUsers': ['all'], 'Filters': ['a', 'b'], 'ImageIds': ['ami-26ebbc5c'], 'Owners': ['309956199498']}

In your case, it sounds like you'd want to conditionally update the describe_kwargs dict with each of the Owners and ImageIds keys, based on whether "they are provided upstream".

amcelwee
  • 1,175
  • 1
  • 9
  • 10