Skip to content

Instantly share code, notes, and snippets.

@wesleymonaro
Created September 2, 2020 01:17
Show Gist options
  • Save wesleymonaro/94347cdd089a75d209498901f2a5d18a to your computer and use it in GitHub Desktop.
Save wesleymonaro/94347cdd089a75d209498901f2a5d18a to your computer and use it in GitHub Desktop.
ec2_stop_business_hours.py
import boto3
import sys, traceback
from datetime import datetime
from time import sleep
def stop_ec2_instances():
start_time = datetime.now()
ec2_client = boto3.client('ec2')
regions = ec2_client.describe_regions()
for region in regions['Regions']:
try:
print("Region: " + str(region['RegionName']))
ec2_client = boto3.client('ec2', region_name=region['RegionName'])
instances = ec2_client.describe_instances()
instanceIds = list()
for reservation in instances['Reservations']:
for instance in reservation['Instances']:
if instance['State']['Name'] == "running" and 'Tags' in instance :
for tag in instance['Tags']:
try:
if tag['Key'] == 'working' and tag['Value'] == 'only-business-hours' :
instanceIds.append(instance['InstanceId'])
except:
print "Not expected error: ", traceback.print_exc()
if len(instanceIds) > 0 :
print "Stopping instances: " + str(instanceIds)
ec2_client.stop_instances(InstanceIds=instanceIds, Force=False)
except:
print "Not expected error:", traceback.print_exc()
end_time = datetime.now()
took_time = end_time - start_time
print "Total time of execution: " + str(took_time)
def lambda_handler(event, context):
print('Stopping instances... ')
stop_ec2_instances()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment