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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.