There are a variety of situations where having a microservice available that can manage (Create, start, stop or terminate)EC2 instances at will can be handy. In this article, we are going to see how we can use an AWS Lambda to do such a thing on demand without using any extra servers or instances at all.
we will write a Lambda function that will create an EC2 instance. This Lambda function will be written in Python using the Boto3 library. We will also create a custom Lambda execution policy for our IAM role. When we’re done, we will be able to log in to the new EC2 instance via SSH.
Let’s navigate to AWS Identity and Access Management (IAM) to create a role for our AWS Lambda function.
Select Role > Create Role > Select AWS service
> Select Lambda
As a use case and create a role with the below policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": [
"ec2:*"
],
"Resource": "*"
},
{
"Sid": "VisualEditor2",
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
Functions > Create Function
**Choose or create an execution role**
> SelectUse an existing role
.#aws #automation-testing #aws-lambda #devops #aws-ec2