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.
Successfully complete this lab by achieving the following learning objectives:
- Create a Custom IAM Policy for an IAM Role
- Select the option to create a custom IAM policy from the Lambda console. It will open a new window to the IAM console.
- In the IAM console, click Create policy, select the JSON tab, and delete what is there.
- Copy the provided IAM policy from the Linux Academy downloads link, and paste it in the JSON tab.
- Back in the IAM console under Roles, search for the new policy we just created and add it to our role.
- The new custom IAM policy may take a few minutes to populate, but once it does, select the new policy and add it to the role.
- Add a role name, tags, and description.
- Click Create role.
- Create a Basic Lambda Function
- In the Lambda console, click Create a function.
- Choose Author from scratch, choose Python 3.6 for the runtime, and select the new IAM role we just created in the previous task.
- Delete the provided JSON, and copy and paste the provided Lambda function code. (Remember to paste in your EC2 instance ID into the Lambda function code.)
- Create a Test in the Lambda Console
- In the Lambda console, in the upper right-hand corner, click Test.
- Leave HelloWorld, add an event name, and click Create.
- Before running the test, go back to the EC2 console to verify that the EC2 instance is running.
- Back in the Lambda console, run the test. You will receive verification that the test was successful.
- Back in the EC2 console, verify that the basic Lambda function stopped the EC2 instance.