Skip to main content

Creating a Basic Lambda Function to Shut Down an EC2 Instance

Hands-On Lab

 

Photo of Julie  Elkins

Julie Elkins

AWS Training Architect I in Content

Length

00:30:00

Difficulty

Beginner

In this hands-on lab, we will create a basic Lambda function to shut down an EC2 instance. We will start by creating a custom IAM policy for the IAM role. We will then create a basic Lambda function using the newly created IAM policy and role along with provided Lambda function code. To verfiy that the new Lambda function shuts down our EC2 instance, we will also run a test to make sure it is all working correctly. We have provided an IAM policy and Lambda function code, which is also available in the downloads section of the course.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Creating a Basic Lambda Function to Shut Down an EC2 Instance

Introduction

In this hands-on lab, we will create a basic Lambda function to shut down an EC2 instance.

Solution

Log in to the live AWS environment with the cloud_user credentials provided, and make sure you are in the us-east-1 region.

Create a Basic Lambda Function and a Custom IAM Policy for an IAM Role

  1. Navigate to EC2 > Instances.

  2. Select the running instance.

  3. Copy its instance ID in the Description section, and paste it into a text file. We'll need it later in the lab.

  4. Navigate to Lambda.

  5. Click Create a function.

  6. Make sure the Author from scratch option at the top is selected, and then use the following settings:

    • Function name: EC2shutdown
    • Runtime: Python 3.6
  7. Expand Choose or create an execution role.

  8. Click the IAM console link to create a custom role.

  9. Select AWS service, and then select Lambda.

  10. Click Next: Permissions.

  11. Click Create policy.

  12. On the policy creation page, select the JSON tab.

  13. Delete the existing code, and paste in the following:

    {
     "Version": "2012-10-17",
     "Statement": [
       {
         "Effect": "Allow",
         "Action": [
           "logs:CreateLogGroup",
           "logs:CreateLogStream",
           "logs:PutLogEvents"
         ],
         "Resource": "arn:aws:logs:*:*:*"
       },
       {
         "Effect": "Allow",
         "Action": [
           "ec2:Stop*"
         ],
         "Resource": "*"
       }
     ]
    }
  14. Click Review policy.

  15. Give it a Name and Description of "EC2shutdown".

  16. Click Create policy.

  17. Back in the IAM Management Console, on the role creation page, search for the newly created EC2shutdown role.

  18. Select it, and click Next: Tags.

  19. On the tags page, set the following values:

    • Key: role
    • Value: EC2shutdownlambda
  20. Click Next: Review.

  21. On the review page, give it a Role name of "EC2shutdownrole".

  22. Click Create role.

  23. Back in the Lambda Management Console, set the Execution role dropdown to Use an existing role.

  24. Hit refresh next to the Existing role dropdown, and then click to select EC2shutdownrole.

  25. Click Create function.

Create a Test in the Lambda Console

  1. On the EC2shutdown page, click Test.
  2. In the Configure test event dialog, give it an Event name of "EC2shutdown".
  3. Click Create. We should receive verification that the test was successful.
  4. Back on the EC2shutdown page, scroll down to the Function code section, and delete the existing code.
  5. Paste in the following Lambda function code:

    import boto3
    #This simple lambda function is available from AWS with instructions on starting and stopping an instance at regular intervals using Lambda and CloudWatch: https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/
    # 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'] you can comma separate the instance IDs for more than one instance: i.e. ['X-XXXXXXXXX', 'X-XXXXXXXXX"]
    instances = ['i-0902effe70a087ae7']
    
    def lambda_handler(event, context):
       ec2 = boto3.client('ec2', region_name=region)
       ec2.stop_instances(InstanceIds=instances)
  6. Replace the instance ID currently in the instances line with the EC2 instance ID you copied earlier.
  7. Click Save.
  8. In a new browser tab, navigate to EC2 > Instances. Our instance should still be running.
  9. On the EC2shutdown page, click Test again. We should receive verification that the test was successful.
  10. Back in the EC2 instances page, we should see our instance has stopped.

Conclusion

Congratulations on successfully completing this hands-on lab!