Skip to content

Instantly share code, notes, and snippets.

@lloiacono
Created December 14, 2017 13:40
Show Gist options
  • Save lloiacono/ee1061c67d26d520d3c18bbf739f2176 to your computer and use it in GitHub Desktop.
Save lloiacono/ee1061c67d26d520d3c18bbf739f2176 to your computer and use it in GitHub Desktop.
Labda function to shut down EC2 instances with a given tag
import boto3
region = 'eu-central-1'
testing_vpc_id = 'vpc-2352384b'
client = boto3.client('ec2', region_name=region)
def get_instances_in_vpc(vpc_id):
response = client.describe_instances(Filters=[{'Name': 'vpc-id',
'Values': [vpc_id]}])
return response['Reservations']
def get_stopped_instances_in_vpc(reservations):
instance_to_be_stopped = []
for reservation in reservations:
for instance in reservation['Instances']:
if instance['State']['Name'] == 'running':
for running_instance in instance['Tags']:
if(running_instance['Key'] == 'environment' and running_instance['Value'] == 'testing'):
instance_to_be_stopped.append(instance['InstanceId'])
return instance_to_be_stopped
def lambda_handler(event, context):
reservations_in_vpc = get_instances_in_vpc(testing_vpc_id)
instances_to_stop = get_stopped_instances_in_vpc(reservations_in_vpc)
client.stop_instances(
DryRun=False,
InstanceIds=instances_to_stop
)
print 'Stopped Instances: ' + str(instances_to_stop)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment