0
votes

I'm looking for a way to mimic the AWS CLI EC2 Filter using Boto3 let say i want to translate the filters portion of describe-instances command:

aws ec2 describe-instances --filters "Name=instance- 
type,Values=m1.small,t2.small"

into Boto3 describe_instances method:

response = client.describe_instances(
    Filters=[
        {
            'Name': 'instance- type',
            'Values': [
                'm1.small','t2.small',
            ]
        }
      ]
    )

So basically what i'm asking, what is good why in python to take the string:

"Name=instance-type,Values=m1.small,t2.small"

and convert it to:

[
  {
     'Name': 'instance- type',
     'Values': [
       'm1.small','t2.small',
     ]
  }
]

so that i can use it as a filter parameter in boto3's decribe_instances method.

2
It would be easy to use regex to break-apart the input expression to the output you've shown, but you really need to consider more potential inputs to create something that will work in most situations. For example, what if there is more than one Filter? Also, why are you wanting to do this? There might be a better option if you explained your ultimate goal.John Rotenstein
the goal is to create a function the has a filter parameter. can be multiple filters.itai majlin
For use with AWS, or for you own purposes? If there are multiple filters, what is the input format?John Rotenstein
For use with aws. looking to mimic the aws cli input format. To simplify things lets go with a single filteritai majlin

2 Answers

0
votes

for cases where filter has multiparts seperated with a ; since the "Name" and "Values" are specific to this filter

def parse_filter_field(filter_str):
    filters = []
    regex = re.compile(r'name=([\w\d_:.-]+),values=([/\w\d_,.\*]+)', flags=re.I)
    for f in filter_str.split(';'):
        match = regex.match(f)
        if match is None:
            print 'could not parse filter: %s' % (f, )
            continue

        filters.append({
            'Name' : match.group(1),
            'Values' : match.group(2).split(',')
            })

return filters
0
votes

The following will match the exact format given, but will run into problems if the format varies too much:

import re

filter='Name=instance-type,Values=m1.small,t2.small'

match = re.search('(.*)=(.*),(.*)=(.*)', filter)

f = {match.group(1) : match.group(2), match.group(3) : match.group(4).split(',')}

# f is a normal Python dictionary
print (f)

# Or, convert it to JSON
import json
print (json.dumps(f))

Output is:

{'Values': ['m1.small', 't2.small'], 'Name': 'instance-type'}
{"Values": ["m1.small", "t2.small"], "Name": "instance-type"}

Order doesn't matter for a dictionary. You can also wrap the output in '[]', but that makes it not strictly JSON.

A great site for testing Python regex expressions: Pythex