EC2 provisioning with Lambda Function
AWS LAMBDA
AWS Lambda is a serverless compute service. We run code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes. Run code for virtually any type of application or backend service. Just upload your code as a ZIP file or container image, and Lambda automatically allocates compute execution power and runs your code based on the incoming request or event, for any scale of traffic. Write Lambda functions in your favorite language (Node.js, Python, Go, Java, and more) and use both serverless and container tools, such as AWS SAM or Docker CLI, to build, test, and deploy your functions.
Here in this tutorial we learn how we can launch an EC2 instance using AWS Lambda.
The architecture diagram of this tutorial is given below.
Here in this tutorial we learn how we can launch an EC2 instance using AWS Lambda.
Prerequisites:
- Create an IAM Role with any name and give EC2 full access to that role. This role will be assumed by Lambda function to launch the instance.
- Create an AMI and copy the AMI id and paste it in the code which we are going to use in Lambda function.
Following are the steps we have followed in this tutorial.
Task 1 Login to AWS Management Console
Task 2 Create a Lambda Function
2.1 Click on Create a function, select Author from Scratch
2.2 Give the name as “MyEC2LambdaFunction” and Select Python 3.8
2.3 Choose myrole
2.4 We need to configure our lambda function. If you scroll down, you can see the Code source section. Here we need to write some Python code to provision an EC2 instance. You will be using boto3 SDK for AWS to write the python code. Remove the existing code in the lambda_function.py file. Copy the below code and paste it into your lambda_function.py file.
import json
import boto3
import time
from botocore.exceptions import ClientError
def lambda_handler(event, context):
# Provision and launch the EC2 instance
ec2_client = boto3.client('ec2')
try:
response = ec2_client.run_instances(
ImageId='ami-0b69ea66ff7391e80',
InstanceType='t2.micro',
MinCount=1,
MaxCount=1
)
print(response['Instances'][0], "EC2 Instance Created")
return {
'statusCode': 200,
'body': json.dumps("success")
}
except ClientError as e:
print("Detailed error: ", e)
return {
'statusCode': 500,
'body': json.dumps("error")
}
except Exception as e:
print("Detailed error: ", e)
return {
'statusCode': 500,
'body': json.dumps("error")
}
2.5 Click on Deploy button.
2.6 Click on Configuration to see General configuration, and click on the Edit button In the Timeout set seconds as 6 and then click on the Save button.
Task 3: Configure a Test Event
3.1 Click on the Test button.
- In Configure test event page, Give Event Name: Enter EC2
- Leave other fields as default.
- Click on Save button
Task 4: Provision an EC2 Instance using a Lambda Function
- Once the EC2 is configured, we can trigger the lambda manually using this simple test.
- Click on the Test button.
- The lambda function now gets executed and an EC2 instance will be provisioned.
- Once it’s completed, you will be seeing a success message similar to the example shown below. It will display details such as:
Task 5: Check that the EC2 instance launched successfully
- Go to the EC2 page from the services menu.
- Go to Instances in the left menu.
- Please wait until the ec2 instance is in a running state
In conclusion, launching EC2 instances with Lambda functions can significantly streamline your cloud infrastructure management processes, providing greater automation, flexibility, and scalability. By harnessing the power of Lambda, you can automate various tasks, optimize resource allocation, and enhance overall operational efficiency within your AWS environment.
Appreciate your time reading! If you found value in this article, a round of applause (👏) would be fantastic to help others discover it. Feel free to share your insights and comments below; I’m eager to hear your thoughts!