Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to match EC2 instance names not starting with a hyphen (-), so I can to skip instance names starting with a - from the shutdown process. If I use a ^ or *, these basic regex operators work fine, but if I try to use more advanced pattern matching, it's not matching properly. The pattern [a-zA-Z0-9] is being 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()
like image 707
Robert Szot Avatar asked Jun 06 '17 17:06

Robert Szot


Video Answer


1 Answers

When using the CLI and various APIs, EC2 instance filtering is not done by "regex". Instead, the filters are simple * and ? wildcards.

According to this document, Listing and Filtering Your Resources, it does mention regex filtering. However, it's unclear in that section whether it's supported in the APIs or just the AWS Management Console.

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

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.

In this section, there is no mention of regex support.

Conclusion, I suspect that regex filtering is only supported in the Management Console UI.

like image 190
Matt Houser Avatar answered Oct 20 '22 02:10

Matt Houser