Automating EC2 with AWS Lambda: Hands-On Guide
Introduction
This tutorial will guide you through automating AWS Elastic Compute Cloud (EC2) tasks using AWS Lambda. AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. By the end of this tutorial, you'll know how to set up a Lambda function to automate simple EC2 tasks.
Prerequisites
- An AWS account.
- Basic familiarity with AWS EC2 and AWS Lambda.
Objective
Create a Lambda function to automatically stop an EC2 instance at a scheduled time.
Step-by-Step Guide
Step 1: Set Up IAM Role for Lambda
- Go to IAM Console: Open the AWS IAM console.
- Create a New Role: Click on "Roles" then "Create role". Select AWS service as the type of trusted entity and choose Lambda.
- Attach Policies: Attach the
AmazonEC2FullAccess
policy. This will allow Lambda to interact with EC2 instances. - Name the Role: Give your role a name, e.g., "lambda_ec2_role", and create the role.
Step 2: Create a Lambda Function
- Open Lambda Console: Go to the AWS Lambda console.
- Create Function: Click on "Create function". Select "Author from scratch".
- Configure Function: Name your function, e.g., "StopEC2Instance". Choose Python 3.x for the runtime. Select the IAM role created in Step 1.
- Create Function: Click on "Create function".
Step 3: Add Python Code to Lambda
- Code Editor: In the function editor, enter the following Python code:
import boto3
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name='your-region')
instances = ['your-instance-id']
ec2.stop_instances(InstanceIds=instances)
return 'Stopped your instances: ' + str(instances)
- Replace
'your-region'
with your EC2 instance's region (e.g., 'us-west-2'). - Replace
'your-instance-id'
with your EC2 instance ID.
Step 4: Test the Lambda Function
- Configure Test Event: In the Lambda console, create a new test event with any sample JSON, as the input isn't relevant for this function.
- Test the Function: Click the "Test" button. If everything is set up correctly, your EC2 instance will stop, and you'll see a success response in the Lambda console.
Step 5: Automate with CloudWatch Events
- Open CloudWatch Console: Go to the Amazon CloudWatch console.
- Create Rule: Go to "Rules" under "Events" and click "Create rule".
- Define Event: Choose "Schedule", set the desired interval or use a cron expression for precise timing.
- Set Target: Choose "Lambda function" as the target and select your Lambda function.
- Configure Details: Name your rule, e.g., "StopEC2Nightly", and create it.
Conclusion
Your AWS Lambda function is now set up and scheduled to automate stopping your EC2 instance. This is a basic example, but the principle can be extended to other automation tasks within AWS, showcasing the power and flexibility of combining Lambda with EC2.