簡體   English   中英

如何在boto3中模擬AWS CLI EC2過濾器

[英]How to mimic AWS CLI EC2 filter in boto3

我正在尋找一種使用Boto3模仿AWS CLI EC2過濾器的方法,可以說我想翻譯describe-instances命令的過濾器部分:

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

進入Boto3 describe_instances方法:

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

所以基本上我要問的是什么,為什么在python中采用字符串:

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

並將其轉換為:

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

這樣我就可以將其用作boto3的decribe_instances方法中的過濾器參數。

以下將與給定的確切格式匹配,但是如果格式變化太大,則會出現問題:

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

輸出為:

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

順序與字典無關。 您也可以將輸出包裝在'[]'中,但這並不完全是JSON。

一個測試Python regex表達式的好網站: Pythex

如果過濾器有多個部分分開了; 因為“名稱”和“值”特定於此過濾器

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM