0
votes

I've created a lampda function for stopping ec2 instances with a specific tag, python code is presented below. Main task of this solution is to stop all instances with a tag "name: purpose, value: temp". When I execute this script all ec2 instances are being stopped. I suppose that something is wrong with this following filter instances = ec2.instances.filter(Filters=[{'Name': 'tag:purpose', 'Values': ['temp']}]). Function code below:

import boto3
def lambda_handler(event, context):
    client = boto3.client('ec2')
    ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
    for region in ec2_regions:
        ec2 = boto3.resource('ec2',region_name=region)
        instances = ec2.instances.filter(Filters=[{'Name': 'tag:purpose', 'Values': ['temp']}])
        RunningInstances = [instance.id for instance in instances]
        for i in RunningInstances:
            stoppingInstances = ec2.instances.stop(i)

2

2 Answers

1
votes

Your filter for tags is wrong you will need to change it:

    filters = [{
        'Name': 'tag:Name',
        'Values': ['Shut']
    },
        {
            'Name': 'instance-state-name',
            'Values': ['running']
    }
    ]

Here is complete working example:

import boto3

#define the connection
ec2 = boto3.resource('ec2')


def lambda_handler(event, context):
    # Use the filter() method of the instances collection to retrieve
    # all running EC2 instances.
    filters = [{
        'Name': 'tag:Name',
        'Values': ['Shut']
    },
        {
            'Name': 'instance-state-name',
            'Values': ['running']
    }
    ]

    #filter the instances
    instances = ec2.instances.filter(Filters=filters)

    #locate all running instances
    RunningInstances = [instance.id for instance in instances]

    #print the instances for logging purposes
    #print RunningInstances

    #make sure there are actually instances to shut down.
    if len(RunningInstances) > 0:
        #perform the shutdown
        shuttingDown = ec2.instances.filter(
            InstanceIds=RunningInstances).stop()
        print(shuttingDown)
    else:
        print("No Instances to shut down")
0
votes

Try this code. I have made a small change

  import boto3
  def lambda_handler(event, context):
  client = boto3.client('ec2')
  ec2_regions = [region['RegionName'] for region in client.describe_regions(['Regions']]
  for region in ec2_regions:
      ec2 = boto3.resource('ec2',region_name=region)
       instances = ec2.describe_instances(Filters=[{'Name': 'tag:purpose', 'Values': ['temp']}]) #you can try by adding describe_instances()
       RunningInstances = [instance.id for instance in instances]
       for i in RunningInstances:
          stoppingInstances = ec2.instances.stop(i)