Skip to content

Instantly share code, notes, and snippets.

@akinom
Created September 28, 2017 13:58
Show Gist options
  • Save akinom/b570a2db867f133d32905ef974d464d8 to your computer and use it in GitHub Desktop.
Save akinom/b570a2db867f133d32905ef974d464d8 to your computer and use it in GitHub Desktop.
AWS lambda to start/stop tagged EC2 instances
import sys, argparse
import boto3
# { "action" : "stop", "tag" : "Managed", "value" : "True", "dryrun" : false }
from argparse import RawDescriptionHelpFormatter
def __manage(event):
__log("PARAMS\taction: %s\tTag: %s=%s\tDryRun=%s" %
(event['action'], event['tag'], event['value'], str(event['dryrun'])))
ec2 = boto3.resource('ec2')
tagfilter = [{
'Name': ("tag:%s" % event['tag']),
'Values': [event['value']]
}]
state = "stopped" if (event['action'] == "start") else "running";
for i in ec2.instances.filter(Filters=tagfilter):
if (i.state['Name'] == state):
if (event['dryrun']):
__log("DRYRUN\taction: %s\t%s" % (event['action'], i))
else:
__log("APPLY\taction: %s\t%s" % (event['action'], i))
if (event['action'] == "start"):
i.start()
else:
i.stop()
else:
__log("NOOP \taction: %s\t%s\t instance in state: %s" % (event['action'], i, i.state))
def __log(str):
print(str)
def lambda_handler(event, context):
"""expects parameters
:param event: hash with 'action', 'tag', 'value', and 'dryrun' keys
:param context:
:return:
"""
__manage(event)
def main(args):
description = """
look for all instances with the given tag value and apply the given state change
unless the instance is already in the given state
"""
parser = argparse.ArgumentParser(description=description,
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('-t', '--tag', required=True, help='name of tag to look for')
parser.add_argument('-V', '--value', required=True, help='tag value to look for (string)')
parser.add_argument('-y', '--dryrun', action='store_true',
help='dry run only - do not apply given action to matching instances')
parser.add_argument('action', nargs=1, help='start or stop')
args = parser.parse_args()
event = { 'tag': args.tag, 'value' : args.value, 'dryrun' : args.dryrun, 'action' : args.action[0]}
__manage(event)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment