How to use extended regex on boto3 ec2 ​​instance?

I'm trying to match EC2 instance names that don't start with a hyphen (-), so I can skip instance names that start with a - from the shutdown process. If I use ^ or * these basic regex operators work fine, but if I try to use more advanced pattern matching it doesn't match as expected. Pattern [a-zA-Z0-9] is ignored and returns no instances.

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

      

+3


source to share


1 answer


When using the CLI and various APIs, EC2 instances are not filtered using "regex". Instead, filters are simple symbols *

and ?

.

According to this document Listing and Filtering Your Resources , it mentions regex filtering. However, it is not clear in this section if it is supported in the API or simply in the AWS Management Console.

However, later in the same document under "Listing and Filtering Using the CLI and API" it says:



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

This section does not mention regular expression support.

Conclusion, I suspect that regex filtering is only supported in the management console interface.

+2


source







All Articles