AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you. You can use AWS Lambda to extend other AWS services with custom logic or create your own back-end services that operate at AWS scale, performance, and security.

In this tutorial, we will write a lambda function that will create an EC2 instance. This lambda function will be written in python using the Boto3 library.

Steps:-

  • Create EC2 Key Pair.
  • Create Lambda function.
  • Change the existing IAM Policy.
  • Adding Python script in lambda function.
  • Test Your Lambda function.
  • Connect it using putty/kitty.

Step 1- Create EC2 Key Pair

In the navigation pane, under “NETWORK & SECURITY”, choose “Key Pairs”.

Click “Create Key pair”

Enter the desire name for your Keypair and save it as ppk format.

Step 2- Create Lambda function

Navigate to the lambda service in AWS Console

Click “Create Function”

Chose “Author from scratch”
Add the Basic information:-

Function name – CreateEC2Instance
Runtime – python 3.8
Exection Role – Create a new role with basic Lambda permissions

Click “Create Function”

As you can see your Lambda Function Is created

Step 3- Change the existing IAM Policy

Navigate to IAM
On the right side menu click on “Role” and search for role that we just created (in my casethe role is CreateEc2Instance-role-lii937g3)

Click on this role(CreateEc2Instance-role-lii937g3) and change the existing Json policy,
Click “Edit Policy”

Replace the existing policy with this:

{
  "Version": "2012-10-17",
  "Statement": [{
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Action": [
        "ec2:RunInstances"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

Review and save

Note– If you use the existing IAM policy then it will through an error saying you are not authorized to perform this operation. ([ERROR] ClientError: An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation).

Step 4- Adding Python script in lambda function.

Back to lambda console
On the create CreateEc2Instance page, scroll down to function code and paste the below code:

import boto3

AMI = 'ami-04b2519c83e2a7ea5'
INSTANCE_TYPE = 't2.micro'
KEY_NAME = 'EC2Instance'
REGION = 'ap-south-1'


ec2 = boto3.client('ec2', region_name=REGION)


def lambda_handler(event, context):

    instance = ec2.run_instances(
        ImageId=AMI,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_NAME,
        MaxCount=1,
        MinCount=1
    )
    
    print ("New instance created:")
    instance_id = instance['Instances'][0]['InstanceId']
    print (instance_id)

    return instance_id

Copy the AMI from the instance launch page and Keyname from that we created in Step 1

Click “save”

Step 5 – Test your Lambda function

Click Test on the Top Right.
Define an empty test event. Its contents can simply be {}.

Click “create”
Click “Test”
It shows the response below:

See the last line you will get the instance id for cross check. In our case instance id is
i-08fbfd72d2bb207c1.

Navigate to Ec2 console and check the instance its running

for cross checking, check the instance Id that we see while the lambda function is executed is the same as the in the running instance .

Step 5- Connect the instance via Putty/Kitty

Note:- Make sure the port 22 is enable from the Security Group

Kudus.. You Successfully follow all the steps and created an EC2 instance with the help of Lambda function and Python boto3 .

Your email address will not be published. Required fields are marked *