Created
September 2, 2020 00:54
-
-
Save wesleymonaro/b3e3668d2d722a4b06fba3858cfe5d00 to your computer and use it in GitHub Desktop.
ec2_start_business_hours
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
import sys, traceback | |
from datetime import datetime | |
from time import sleep | |
def start_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'] == "stopped" 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 "Starting instances: " + str(instanceIds) | |
ec2_client.start_instances(InstanceIds=instanceIds) | |
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('Starting instances... ') | |
start_ec2_instances() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment