如何在 boto3 ec2 实例过滤器中使用高级正则表达式?

How can I use advanced regex in a boto3 ec2 instance filter?

我正在尝试匹配不以连字符 (-) 开头的 EC2 实例名称,因此我可以在关闭过程中跳过以 - 开头的实例名称。如果我使用 ^ 或 *,这些基本的正则表达式运算符可以正常工作,但如果我尝试使用更高级的模式匹配,则匹配不正确。模式 [a-zA-Z0-9] 被忽略并且 returns 没有实例。

import boto3

# Enter the region your instances are in, e.g. 'us-east-1'
region = 'us-east-1'

#def lambda_handler(event, context):
def lambda_handler():

    ec2 = boto3.resource('ec2', region_name=region)

    filters= [{
        'Name':'tag:Name',
        #'Values':['-*']
        'Values':['^[a-zA-Z0-9]*']
        },
        {
        'Name': 'instance-state-name',
        'Values': ['running']
        }]

    instances = ec2.instances.filter(Filters=filters)

    for instance in instances:
        for tags in instance.tags:
            if tags["Key"] == 'Name':
                name = tags["Value"]

        print 'Stopping instance: ' + name + ' (' + instance.id + ')'
        instance.stop(DryRun=True)

lambda_handler()

使用 CLI 和各种 API 时,EC2 实例过滤不是由 "regex" 完成的。相反,过滤器是简单的 *? 通配符。

根据这篇文档,Listing and Filtering Your Resources,它确实提到了正则表达式过滤。但是,该部分并不清楚它是在 API 中受支持还是仅在 AWS 管理控制台中受支持。

但是,稍后在同一文档中,在 "Listing and Filtering Using the CLI and API" 中,它说:

You can also use wildcards with the filter values. An asterisk (*) matches zero or more characters, and a question mark (?) matches exactly one character. For example, you can use database as a filter value to get all EBS snapshots that include database in the description.

本节未提及正则表达式支持。

结论,我怀疑只有管理控制台支持正则表达式过滤UI。

我试过这样的事情:

snap_response = ec2_client.describe_snapshots(
    Filters=[
        {
            'Name': 'tag:'+tag_key,
            'Values': [tag_value+'*']
        },
    ],
)

它 returns 我需要的值。

我刚试过 ?和 * 过滤器值中的字符,它就像一个魅力..!

ec2_result = ec2_client.describe_instances(
    Filters=[
        {
            'Name': 'tag:Application',
            'Values': ['?yApp*']
        }
    ]
)