如何在boto3中模拟AWS CLI EC2过滤器

2024-10-05 10:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在寻找一种使用Boto3模拟awsclieec2过滤器的方法 假设我要转换describe instances命令的过滤器部分:

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

在Boto3中描述_实例方法:

^{pr2}$

所以基本上我要问的是,为什么在python中使用字符串:

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

并将其转换为:

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

这样我就可以在boto3的decribe_instances方法中使用它作为过滤器参数。在


Tags: instances方法instancename命令aws过滤器type
2条回答

以下内容将与给定的格式完全匹配,但如果格式变化太大,则会出现问题:

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))

输出为:

^{pr2}$

字典的顺序并不重要。您也可以将输出包装在'[]'中,但这使得它不是严格的JSON。在

一个测试Python正则表达式的好站点:Pythex

对于过滤器有多个部分与a分开的情况; 因为“Name”和“Values”是特定于此筛选器的

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

相关问题 更多 >

    热门问题