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