AWS, CloudAWS – Start EC2 using Lambda and cron

AWS – Start EC2 using Lambda and cron

Amazon Elastic Compute Cloud (Amazon EC2) web service provides need based compute capacity in the cloud. Server can be scheduled to boot up at a particular time and then go back to sleep. Every time an instance starts and stops Amazon assigns it a new public IP address. However, it is not possible to manually start and stop an instance every time a new IP is assigned.

Become AWS Expert
Ad

The solution is assign a tag to the EC2 instance(s) and then create a lambda function as below which will start the EC2 instance(s) having that tag.

The Lambda can be scheduled to run automatically by setting anevent in CloudWatch. Note: AWS cron is GMT based.
Refer to aws lambda tutorial how to create a lambda function

Python lambda – to get instance-id and automatically start the instance.

Lines 2-5. Import python packages
Line 8. Set the region
Line 10. Start the function
Lines 11-14. Search EC2 instance that has Tag key as NameG

Line 16. Initialize list to store fetched instance-ids
Lines 17-20. Get all EC2 hosts that have Tag=NameG. In this case only one will be found.
Line 22. Start the EC2 instance
Line 24. Sleep for 30 seconds to allow instance to come up fully
Line 26. Send notification to SNS

import json
import boto3
import os
import time
#Enter the region your instances are in. 
#Include only the region without specifying Availability Zone; 
#e.g.; 'us-east-1'
region = 'us-east-1'

def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=region)
    instDict=ec2.describe_instances(
        Filters=[{"Name": "tag-key", "Values": ["NameG"]}]
        )
    #print instDict['Reservations']
    hostList=[]
    for r in instDict['Reservations']:
        #print r
        for inst in r['Instances']:
            hostList.append(inst['InstanceId'])
            
    ec2.start_instances(InstanceIds=hostList)
    
    time.sleep(30)

Setting cron in CloudWatch to automatically run Lambda function


Categories: AWS, Cloud Tags:

Comments

No Comments Yet. Be the first?

Post a comment

Your email address will not be published. Required fields are marked *