Skip to content

Instantly share code, notes, and snippets.

@MaxBarraclough
Last active May 10, 2020 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MaxBarraclough/211e569cb57b46c0ddb481f6adcefdd1 to your computer and use it in GitHub Desktop.
Save MaxBarraclough/211e569cb57b46c0ddb481f6adcefdd1 to your computer and use it in GitHub Desktop.
Amazon Lambda script: start all appropriately tagged instances
## Amazon Lambda script: start all appropriately tagged instances
##
## Runs in Amazon Lambda as Python 2.7 or as Python 3.6.
## Intended to be invoked on a schedule by Amazon Cloud Watch.
## Tag relevant instances with label 'autostart', value 'true'.
## TODO It could be good to add logging to this script
import boto3
region = 'eu-west-1' ## Ireland
def lambda_handler(event, context):
## Don't call anything just 'ec2', that's confusing
ec2_resource = boto3.resource('ec2', region_name=region)
ec2_client = boto3.client('ec2', region_name=region)
filters = [{
'Name': 'tag:autostart',
'Values': ['true']
}
]
to_start = ec2_resource.instances.filter(Filters=filters)
to_start_ids = [instance.id for instance in to_start]
ec2_client.start_instances(InstanceIds=to_start_ids)
# May want broad rights from the 'execution role'. I used this JSON, based on
# https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html
# {
# "Version": "2012-10-17",
# "Statement": [
# {
# "Effect": "Allow",
# "Action": [
# "ec2:*"
# ],
# "Resource": "*"
# }
#
# ]
# }
## (MIT Licence)
##
## Copyright 2018 Max Barraclough
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
## in the Software without restriction, including without limitation the rights
## to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
## copies of the Software, and to permit persons to whom the Software is
## furnished to do so, subject to the following conditions:
##
## The above copyright notice and this permission notice shall be included in
## all copies or substantial portions of the Software.
##
## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
## THE SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment