Lambda Function to Shut Down and Terminate an EC2 Instance

Launching Lab Environment

  1. Make sure to sign out of the existing AWS Account before you start a new lab session (if you have already logged into one). Check FAQs and Troubleshooting for Labs, if you face any issues.

  2. Launch lab environment by clicking on . This will create an AWS environment with the resources required for this lab.

  3. Once your lab environment is created successfully,  will be active. Click on . This will open your AWS Management Console Account for this lab in a new tab. If you are asked to log out in AWS Management Console page, click the here link and then click on  again.

Note : If you have completed one lab, make sure to sign out of the AWS account before starting a new lab. If you face any issues, please go through FAQs and Troubleshooting for Labs.

Steps

Launching two EC2 Instances

  1. Make sure you are in the N.Virginia Region.

  2. Navigate to EC2 by clicking on the  menu at the top, then click on  in the  section.

  3. Navigate to on the left panel and click on 

    1. Search and Choose Amazon Linux 2 AMI: 

  4. Choose an Instance Type: Select  and then click on the 

  5. Configure Instance Details: 

    • Number of Instances: Enter 2

  1. Click on  and then click on 

  2. Key Pair: Select Proceed without a Key pair and check I acknowledge checkbox

  1. Click on 

  2. Navigate back to the Instance page and you will be able to see two EC2 instances launched. 

  1. Select any one EC2 Instance and click on 

  2. Click on  , select Stop and then click on 

Create an IAM Role

  1. Go to  and select .

  2. In the left menu, click on . Click on the  button.

    • Select from the AWS Services list.

    • Click on .

    • Type EC2fullaccess in the search bar and then choose 

  • Click on the .

     3. Add Tags: Provide a key-value pair for the role:

  • Key: name

  • Value: myec2role

  • Click on the 

     4.Role Name: 

  • Role name : Lambda_ec2_status
  • Click on the  button.
  1. You have successfully created an IAM role named Lambda_ec2_status.

Create a Lambda Function

  1. Go to  menu, click on 

  2. Make sure you are in the US East (N. Virginia) region.

  3. Click on the  button.

    • Choose .

    • Function name        : myEC2LambdaFunction

    • Runtime: Select Python 3.8

    • Permissions: click on the  and choose 

    • Existing role: Select Lambda_ec2_status from the dropdown list.

    • Click on 

  4. Configuration Page: Here we need to configure our lambda function. If you scroll down, you can see the Function code section. Here we need to write some Python code that will shut down and terminate an EC2 instance.

  5. You will be using boto3 SDK for AWS to write the python code.

  6. Remove the existing code in AWS lambda lambda_function.py. Copy the below code and paste it into your lambda_function.py file.

 

import json

import boto3

 

def lambda_handler(event, context):

    region = 'us-east-1'

    client = boto3.client("ec2", region_name=region)

    status = client.describe_instance_status(IncludeAllInstances = True)

    

    for i in status["InstanceStatuses"]:

        

        instaId = list(i["InstanceId"].split(" "))

        if i["InstanceState"]["Name"] == "running":

            print("Instances status : ", i["InstanceState"]["Name"])

            client.stop_instances(InstanceIds=instaId)

            print("Stopping the instance",i["InstanceId"])

            

        elif i["InstanceState"]["Name"] == "stopped":

            print("Instances status : ", i["InstanceState"]["Name"])

            client.terminate_instances(InstanceIds=instaId)

            print("Terminating the instance",i["InstanceId"])

            

        elif i["InstanceState"]["Name"] == "terminated":

            print("Terminated the instance",i["InstanceId"])

            

        else:

            print("Please wait for the instance to be stopped or running state")

        print("\n")

        

        

    

    return {

        'statusCode': 200,

    }

 

  1. Save the function by clicking on  in the top-right corner.

Configure Test Event

  1. Click on the Test button at the top-right corner of the configuration button.

  2. On the Configure test event page,

    • Event Name: Enter myEC2Test

    • Leave other fields as default.

    • Click on .

Performing Stop and Terminate actions on EC2 Instances

  1. Once the EC2Test is configured, we can trigger the lambda using a simple manual test.

  2. Click on the Test button. 

  3. The lambda function will be executed, the running EC2 instance will be stopped and the stopped instance will be terminated.

  4. Once it completes, you will be seeing a success message (as shown below).

Check the EC2 instance's status

  1. Navigate to the EC2 page from the services menu.

  2. Go to Instances in the left menu.

  3. You can see that the running instance is stopped and the stopped instance is terminated.

Performing Stop and Terminate action again

  1. Navigate to the  and select myEC2LambdaFunction.

  2. Click on the Test button again. 

  1. The lambda function will be executed again and the stopped EC2 instance will be Terminated.

  2. Once it completes, you will be seeing a success message (as shown below).

Check the EC2 instance's status again

  1. Navigate to the EC2 page from the services menu.

  2. Go to Instances in the left menu.

  3. You can see that the running instance is stopped and the stopped instance is terminated.

 

Completion and Conclusion

  1. You have created two EC2 Instances.

  2. You have created an IAM role for the Lambda function.

  3. You have created a Lambda function with boto3 python code.

  4. You have configured a test event and triggered it manually.

  5. You have successfully shut down and terminated the EC2 instance.

End Lab

  1. Sign out of AWS Account.

  2. You have successfully completed the lab.

  3. Once you have completed the steps click on  from your whizlabs dashboard.



Join Whizlabs_Hands-On to Read the Rest of this Lab..and More!

Step 1 : Login to My-Account
Step 2 : Click on "Access Now" to view the course you have purchased
Step 3 : You will be taken to our Learn Management Solution (LMS) to access your Labs,Quiz and Video courses