Skip to content

Instantly share code, notes, and snippets.

@uolter
Last active January 23, 2018 10:27
Show Gist options
  • Save uolter/3a7cc2b64cad9d1e0fd064d810ae201d to your computer and use it in GitHub Desktop.
Save uolter/3a7cc2b64cad9d1e0fd064d810ae201d to your computer and use it in GitHub Desktop.
AWS lambda which stops EC2 instances with Env Dev tag
import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'eu-west-1'
filters = [{'Name':'tag:Env', 'Values':['Dev']}]
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=region)
instances = [instance.id for instance in boto3.resource('ec2').instances.filter(Filters=filters)]
ec2.stop_instances(InstanceIds=instances)
print 'stopped your instances: ' + str(instances)
"""
ec2.start_instances(InstanceIds=instances)
print 'started your instances: ' + str(instances)
"""
if __name__ == "__main__":
lambda_handler({},None)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:Start*",
"ec2:Stop*"
],
"Resource": "*"
},
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment