Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1. import boto3
  2. import logging
  3.  
  4. #setup simple logging for INFO
  5. logger = logging.getLogger()
  6. logger.setLevel(logging.INFO)
  7.  
  8. #define the connection
  9. ec2 = boto3.resource('ec2')
  10.  
  11. def lambda_handler(event, context):
  12.     # Use the filter() method of the instances collection to retrieve
  13.     # all running EC2 instances.
  14.     filters = [{
  15.             'Name': 'tag:AutoOff',
  16.             'Values': ['True']
  17.         },
  18.         {
  19.             'Name': 'instance-state-name',
  20.             'Values': ['running']
  21.         }
  22.     ]
  23.    
  24.     #filter the instances
  25.     instances = ec2.instances.filter(Filters=filters)
  26.  
  27.     #locate all running instances
  28.     RunningInstances = [instance.id for instance in instances]
  29.    
  30.     #print the instances for logging purposes
  31.     #print RunningInstances
  32.    
  33.     #make sure there are actually instances to shut down.
  34.     if len(RunningInstances) > 0:
  35.         #perform the shutdown
  36.         shuttingDown = ec2.instances.filter(InstanceIds=RunningInstances).stop()
  37.         print shuttingDown
  38.         ec2.create_tags(InstanceIds=RunningInstances, Tags=[{'Key': 'MonitoringEnabled', 'Value': False}])
  39.     else:
  40.         print "Nothing to see here"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement