如何在boto3 ec2实例过滤器中使用高级regex?

2024-05-18 14:50:19 发布

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

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

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

Tags: instances实例instancelambdanamein名称tags
3条回答

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

根据本文Listing and Filtering Your Resources,它确实提到了regex过滤。但是,在这一节中,还不清楚它是在api中受支持,还是仅仅在AWS管理控制台中受支持。

但是,在同一文档的后面部分,在“使用CLI和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.

在本节中,没有提到regex支持。

结论,我怀疑regex过滤仅在管理控制台UI中受支持。

我试过这样的方法:

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

它返回我需要的值。

我刚试过?和*字符的过滤值和它的工作就像一个魅力。。!

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

相关问题 更多 >

    热门问题