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

标签 python amazon-web-services amazon-ec2 boto boto3

我正在尝试匹配不以连字符 (-) 开头的 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()

最佳答案

使用 CLI 和各种 API 时,EC2 实例过滤不是由“正则表达式”完成的。相反,过滤器是简单的 *? 通配符。

根据这份文件,Listing and Filtering Your Resources ,它确实提到了正则表达式过滤。但是,该部分并不清楚它是在 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.

在本节中,没有提及正则表达式支持。

结论,我怀疑正则表达式过滤仅在管理控制台 UI 中受支持。

关于python - 如何在 boto3 ec2 实例过滤器中使用高级正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44396578/

相关文章:

python - 当使用 Pandas 的 "AttributeError: ' 方法时,' object has no attribute ' float '"all "where"

amazon-web-services - 为什么我的 ELB 有两个 IP 地址?如何找到它们?

ssh - 将文件从一个 EC2 实例同步到另一个

amazon-web-services - EC2 实例自动重新启动并取消我的弹性 IP 和目标组的关联

python - 在 python 中,从字典列表中删除列表的好方法

python - 通过 SSH 执行 Powershell 命令

python - 将 Base64 图像上传到 S3 并返回 URL

php - 我找到了一个链接,但我不知道那是什么

amazon-web-services - 如何检查我的代码是否在AWS EC2上的容器中运行

python - 随机保留字典的 X 百分比