Skip to content

Instantly share code, notes, and snippets.

@pandaedward
Created October 2, 2019 02:13
Show Gist options
  • Select an option

  • Save pandaedward/116e35e5155659f754dde12ea96e5479 to your computer and use it in GitHub Desktop.

Select an option

Save pandaedward/116e35e5155659f754dde12ea96e5479 to your computer and use it in GitHub Desktop.
lambda python
import boto3
from botocore.exceptions import ClientError
def run(event, context):
client = boto3.client('ec2')
ec2_regions = [region['RegionName'] for region in client.describe_regions()['Regions']]
print("Regions: ", ec2_regions)
for region in ec2_regions:
ec2 = boto3.resource('ec2', region_name=region)
all_instances = [i for i in ec2.instances.filter(Filters=[
{
'Name': 'instance-state-name',
'Values': ['running']
}
])]
if len(all_instances) == 0:
print("No instance is running in ", region)
continue
else:
print("Running instances: ", all_instances)
# Filter list of persistent instances
instances = [i for i in ec2.instances.filter(Filters=[
{
'Name': 'instance-state-name',
'Values': ['running']
},
{
'Name': 'tag:janitor_monitor_status',
'Values': ['run']
}
])]
print("Persistent instances: ", instances)
# Construct list of instances to be stopped
# Invert select
instances_to_stop = [to_stop for to_stop in all_instances if to_stop.id not in [i.id for i in instances]]
if len(instances_to_stop) == 0:
print("No instance to be stopped")
else:
# Loop through to be stopped list
for instance in instances_to_stop:
# Add tag
print("Instance to be stopped: ", instance.id)
tags = {}
for tag in instance.tags or []:
tags[tag['Key']] = tag['Value']
# Check if tag is in
if 'janitor_monitor_status' not in tags:
print("Adding 'janitor_monitor_status' tag key with value 'off' to instance: ", instance)
client.create_tags(
Resources=[
instance.id
],
Tags=[
{
'Key': 'janitor_monitor_status',
'Value': 'off'
}
]
)
try:
print("Stopping instance: ", instance.id)
instance.stop()
except ClientError as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment