Last active
July 17, 2019 19:28
-
-
Save raymyers/6eba18e54163b93c498f37980b4d1b97 to your computer and use it in GitHub Desktop.
Shutdown EC2 instances off hours with AWS Lambda + Serverless framework + Python
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 | |
region = 'us-east-1' | |
def find_instance_ids(ec2): | |
response = ec2.describe_instances(Filters=[ | |
{'Name': "tag:StopOffHours", 'Values': ["yes"]} | |
]) | |
return [ | |
instance['InstanceId'] | |
for reservation in response['Reservations'] | |
for instance in reservation['Instances'] | |
] | |
def stop(event, context): | |
ec2 = boto3.client('ec2', region_name=region) | |
instance_ids = find_instance_ids(ec2) | |
print("Stopping instances: " + str(instance_ids)) | |
ec2.stop_instances(InstanceIds=instance_ids) | |
def start(event, context): | |
ec2 = boto3.client('ec2', region_name=region) | |
instance_ids = find_instance_ids(ec2) | |
print("Starting instances: " + str(instance_ids)) | |
ec2.start_instances(InstanceIds=instance_ids) |
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
service: my-scheduler | |
provider: | |
name: aws | |
runtime: python3.7 | |
region: us-east-1 | |
iamRoleStatements: | |
- Effect: Allow | |
Action: | |
- ec2:Describe* | |
Resource: | |
- "*" | |
- Effect: Allow | |
Action: | |
- ec2:StartInstances | |
- ec2:StopInstances | |
Resource: | |
- arn:aws:ec2:*:*:instance/* | |
Condition: | |
StringEquals: | |
"ec2:ResourceTag/StopOffHours": "yes" | |
package: | |
exclude: | |
- "**/*" | |
include: | |
- "!./**" | |
- handler.py | |
functions: | |
StopOffHours: | |
handler: handler.stop | |
events: | |
- schedule: cron(0 23 ? * MON-FRI *) | |
StartDuringHours: | |
handler: handler.start | |
events: | |
- schedule: cron(0 13 ? * MON-FRI *) | |
plugins: | |
- serverless-python-requirements |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment