Created
August 29, 2018 00:38
-
-
Save hoangvx/d384c9e9a084fe4620aebadd7e960477 to your computer and use it in GitHub Desktop.
auto start and stop aws ec2 instance by setting tags name
This file contains 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 time | |
# Example EC2 Instance tags: | |
# | |
# Scheduled : True | |
# ScheduleStart : 06:00 | |
# ScheduleStop : 18:00 | |
## | |
#define boto3 the connection | |
ec2 = boto3.resource('ec2') | |
def lambda_handler(event, context): | |
print "Check EC2 tags" | |
# Get current time in format H:M | |
current_time = time.strftime("%H:%M") | |
# Find all the instances that are tagged with Scheduled:True | |
filters = [{ | |
'Name': 'tag:Scheduled', | |
'Values': ['True'] | |
} | |
] | |
# Search all the instances which contains scheduled filter | |
instances = ec2.instances.filter(Filters=filters) | |
stopInstances = [] | |
startInstances = [] | |
# Locate all instances that are tagged to start or stop. | |
for instance in instances: | |
for tag in instance.tags: | |
if tag['Key'] == 'ScheduleStop': | |
if tag['Value'] == current_time: | |
stopInstances.append(instance.id) | |
pass | |
pass | |
if tag['Key'] == 'ScheduleStart': | |
if tag['Value'] == current_time: | |
startInstances.append(instance.id) | |
pass | |
pass | |
pass | |
pass | |
print current_time | |
# shut down all instances tagged to stop. | |
if len(stopInstances) > 0: | |
# perform the shutdown | |
stop = ec2.instances.filter(InstanceIds=stopInstances).stop() | |
print stop | |
else: | |
print "No instances to shutdown." | |
# start instances tagged to stop. | |
if len(startInstances) > 0: | |
# perform the start | |
start = ec2.instances.filter(InstanceIds=startInstances).start() | |
print start | |
else: | |
print "No instances to start." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment