[英]How to mimic AWS CLI EC2 filter in boto3
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: 我正在寻找一种使用Boto3模仿AWS CLI EC2过滤器的方法,可以说我想翻译describe-instances命令的过滤器部分:
aws ec2 describe-instances --filters "Name=instance-
type,Values=m1.small,t2.small"
into Boto3 describe_instances method: 进入Boto3 describe_instances方法:
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: 所以基本上我要问的是什么,为什么在python中采用字符串:
"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. 这样我就可以将其用作boto3的decribe_instances方法中的过滤器参数。
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.
您也可以将输出包装在'[]'中,但这并不完全是JSON。
A great site for testing Python regex expressions: Pythex 一个测试Python regex表达式的好网站: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.