Script - Stop Start & Reboot

___
Stop
__
import boto3
# Enter the region your instances are in. Include only the region without specifying Availability Zone; e.g., 'us-east-1'
region = 'us-east-1'
# Enter your instances here: ex. ['X-XXXXXXXX', 'X-XXXXXXXX']
instances = ['i-064ffac2782e94bdf']

def lambda_handler(event, context):
   ec2 = boto3.client('ec2', region_name=region)
   ec2.stop_instances(InstanceIds=instances)
   print 'stopped your instances: ' + str(instances)


___
Start
____
import boto3
import logging

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

#define the connection
ec2 = boto3.resource('ec2',region_name='us-east-1')

def lambda_handler(event, context):
   # Use the filter() method of the instances collection to retrieve
   # all stooped EC2 instances.
   filters = [{
           'Name': 'tag:AutoStartStop',
           'Values': ['True']
       },
       {
           'Name': 'instance-state-name',
           'Values': ['stopped']
       }
   ]
   
   #filter the instances
   instances = ec2.instances.filter(Filters=filters)

   #locate all stopped instances
   StoppedInstances = [instance.id for instance in instances]
   
   #print the instances for logging purposes
   #print StoppedInstances
   
   #make sure there are actually instances to shut down.
   if len(StoppedInstances) > 0:
       #perform the shutdown
       StartingUp = ec2.instances.filter(InstanceIds=StoppedInstances).start()
       print StartingUp
   else:
       print "Nothing to see here"

____
Reboot
____
import boto3
import collections
import datetime
ec = boto3.client('ec2','us-west-2') #mention your region to reboot
def lambda_handler(event, context):
   print "hi"
   reservations = ec.describe_instances( Filters=[ {'Name': 'tag-key', 'Values': ['reboot', 'true']}, ] )
   for r in (reservations["Reservations"]):

      for inst in r["Instances"]:

          print inst["InstanceId"]
          instid=inst["InstanceId"]
          response = ec.reboot_instances( InstanceIds=[ instid, ])

Comments

Popular posts from this blog

How To Know Which Program To Use To Open An Unknown File Extension

Step By Step: Install and Configure Sensu + Grafana

Hosting a WordPress Blog with Amazon Linux