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 Move on the AWS Management Console

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:*:*:*"
        }
    ]
}

Let’s Move on the AWS Lambda

  1. Select Functions > Create Function
  2. Enter the name of your lambda function.
  3. Select python as a runtime language.
  4. Click on **Choose or create an execution role **> SelectUse an existing role.
  5. Click Create Function.
  6. Navigate to AWS Lambda
  7. Select Functions > Create Function
  8. Click on **Choose or create an execution role**> SelectUse an existing role .

#aws #automation-testing #aws-lambda #devops #aws-ec2

AWS Lambda — Launch EC2 Instances
1.25 GEEK