Amazon AWS Lambda Tutorial – Schedule to Stop EC2 Instances

 

Lambda is an event-driven compute service. We have functions that execute when a trigger is triggered. In today’s lab, we will set up a trigger with Cloud watch Events.

On top of that, we will need an IAM role that gives our lambda function permissions to Stop EC2 Instances. We will also add Cloud watch permissions in that role so that the lambda function can log the event every time it is triggered.

Let’s get started with setting up the role:

You should see a list of policies. Search for AmazonEC2FullAccess and check the box.

 

Now we should have a role that we can attach to our Lambda function.

Now Let’s work on our Lambda function:

 

                               import boto3

                               client=boto3.client(‘ec2’)

                               def lambda_handler(event, context):

                               response=client.describe_instances()

                               for reservation in response[“Reservations”]:

                                      for instance in reservation[“Instances”]:

                                           print(instance[“InstanceId”] + “stopping”)

                                           id=[instance[“InstanceId”]]

                               client.stop_instances(InstanceIds=id)

                               return(“Completed”)

 

Cloudwatch Events Setup:

Now let’s go to our EC2 console and launch or start few ( 3 ) instances.

It’s time to test the Lambda Function. Since we can’t wait until 12 am, let’s test the event manually.

Go back to the Lambda function we created earlier and click Test.

Check your EC2 console. Your EC2 instance must be stopping.

That concludes the lab.

Terminate the EC2 instance that you created earlier.

 

*If you have errors in lambda function we can go to cloud watch logs and troubleshoot.

 

 

Want more information on how to become Amazon AWS Certified? Learn more!

 

Exit mobile version