- A Cloud Guru
Creating a Basic Lambda Function to Shut Down an EC2 Instance
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 the 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. The provided IAM policy and Lambda function code can be accessed from the lab guide and in the Additional Information and Resources section of this lab.
Table of Contents
Create a Custom IAM Policy and Role for a Lambda Function
- From the AWS Management Console, navigate to IAM.
- Select the option to create a custom IAM policy for the Lambda service.
- In the IAM console, click Create policy.
- Select the JSON tab and delete the provided JSON.
- Copy the provided IAM policy from the GitHub repo or the lab guide and paste it in the JSON tab.
- In the IAM console under Roles, search for the newly created policy and add it to our role.
Note: The IAM policy may take a few minutes to populate.
- Once populated, select the new policy and add it to the role.
- Add a role name, tags, and a description.
- Click Create role.
Create a Basic Lambda Function
- In the Lambda console, click Create a function.
- Select Author from scratch.
- For the runtime, select Python 3.6.
- Select the newly created IAM role and delete the provided JSON.
- Copy the provided Lambda function code from GitHub or the lab guide and paste it into the role.
- Paste in your EC2 instance ID into the Lambda function code.
Create a Test in the Lambda Console
- In the Lambda console under Code source, select the new function and click Test.
- Add an event name and click Create.
- In the EC2 console, verify the instance is running.
- Return to the Lambda console and run the test.
- Return to the EC2 console and verify that the basic Lambda function stopped the EC2 instance.
What's a lab?
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.