How to start-stop an EC2 instance via Lambda function

First, we have to create I am role that role has permission to start and stop ec2 instance.

Second, we have to create lambda functions.

Third, we have to create CloudWatch event for cron jobs.

Now create two lambda functions, one for start and second for stop to ec2 instance.

How to create lambda functions?

First click on create function

Now define the name of function, runtime(language), select an existing role which we had created and click on create function.

Now, define the lamda_function_code:-

import boto3
region = ‘ap-south-1’
instances = [‘instance’]
ec2 = boto3.client(‘ec2’, region_name=region)
def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=instances)
   print(‘started your instances: ‘ + str(instances))

After this click on deploy and give the name to the event, and test the event.

Now we are going to define the cron job, first go to CloudWatch and select rule under the event section. Select schedule section and then cron section:-

Now click on add targets and select lambda function in drop down section, define the details like which lambda function you want to trigger.

 

How to Install MongoDB on AMAZON Linux, CentOS7, and Redhat.

Leave a Reply

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