Lambda falls under “Compute” service in AWS (Amazon Web Services). Using Lambda we can code without provisioning or managing servers. Lambda automatically runs our code without requiring us to provision or manage servers. We just need to write the code and upload it to the Lambda Function. 

Lambda executes the code only when needed. It grows automatically supporting from a few requests to thousands of requests.

We are charged for every 100ms our code executes and the number of times it is triggered. We are charged only for the compute time our code consumes and not charged when the code is not being executed. To understand more about billing, click here.

What we need to provide is just the code and AWS Lambda takes care of maintenance, auto-scaling, high availability. This code can also be executed in response to events. To use Lambda, we need to write the code in one of the languages provided by it. 

In this article, we will see how to create a simple Lambda function that can start/stop an EC2 instance.

Pre-requisites

  1. AWS Account (Create if you don’t have one)
  2. Basics of EC2 Service(Click here to learn EC2).

What we will do

  1. Login to AWS.
  2. Create a Lambda Function.
  3. Modify IAM Role
  4. Execute the Role

Login to AWS

  1. Click here to go to AWS Login Page.

When we hit the above link, we will see a web page as follows where we are required to login using our login details.

Once we login into AWS successfully, we will see the main console with all the services listed as follows.

Create a Lambda Function

Before proceeding with the creation of a Lambda Function, select the desired and closest region.

Click on the arrow near the default region (Here it is Paris) and you will see a list of regions available and select the desired region. Here, I have selected “Paris”, kept it unchanged. You can select as per your choice or requirement.

Click on “Services” at the upper left corner and you will see the following screen with all the services available on AWS. Click on “Lambda” available under “Compute”

You will get a screen where you can create a Lambda Function. Click on “Create Function”

You can either create a function on your own, use the existing blueprints or browse a repository where we can search for the required function to see if it exists. Here, we will create our own simple Lambda Function using Python.

Click on “Author from Scratch” to write our own Lambda Function.

Provide a name to the Function.

Select “Python 3.6” from the drop-down list of Runtime. 

Lambda Function needs to have sufficient permissions for its execution. Select “Create a new role with basic Lambda Permissions”. This will create a new Role with the same name as that of Function name with some random key as a suffix.

The above default permissions are not enough. We will understand this better in the next step. For now, we shall just create a function and see what possible errors can arise.

Add the following code in the function and click on “Save” button to save the function.

Change the value of “region and instances”.

import boto3

region = 'eu-west-3'

instances = ['i-05be5c0c4039881ed']

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

def lambda_handler(event, context):

    ec2.stop_instances(InstanceIds=instances)

    print('stopped your instances: '   str(instances))

Click on “Select a test Event” button available besides “Test” button and select on “Configure test event”. You will get the following screen. Do not make any changes and just give a name to the event, here it is “testStopEC2” and click on “Save”. This event is just a sample event and does not have any relevance with our function. We can create a different event as per our requirement.

Note: We can create a Cloudwatch event using which we can trigger this Lambda Function based on the event that triggered in Cloudwatch. We won’t disscuss about this now, as it would need clear understanding of Cloudwatch. So we will proceed with a simple event. You can explore this once you get familiar with Lambda and Cloudwatch. 

Now click on “Test”. Notice carefully, the function has failed to execute because of insufficient permission. This is what I was talking about in the previous step. Don’t panic looking at the error. We will assign the required permissions to the role which was created upon creation of the Lambda function.

Modify IAM Role

Click on “Services” at the top-right of the screen and search for IAM.

You will see a screen as follows. This is the main screen of IAM. We won’t go in detail of IAM in this article.

Click on “Roles” from the left panel and click on the Role which starts with the same name as that of Lambda Function name and having some random string as suffix to it.

Click on “Attach policies”

Search for “ec2” in the search  box and select “AmazonEC2FullAccess”  from the list and click on “Attach Policy” button. Now we are all set to execute the Lambda function with the required permissions.

Execute the Lambda Function

Go back to our Lambda function and now click on “Test” Button. This time you can see in the logs that the function has been executed successfully. This means the Lambda function has triggered a request to stop the instance. 

Go to “EC2” service and see if the instance with the instance id we provided to the Lambda function has been stopped or not. Here, you can see that the Instance State is “Stopping” which means the Lambda function has successfully processed our request to stop the required instance.

In the previous steps we saw a Lambda function to stop EC2 instance. Now we will see how EC2 instance can be started using Lambda. To do so, you can either edit the same function or write a new function following the same previous steps.

Here, we shall use the same function and just change our Python code.

Use the following code to start EC2 instance using Lambda.

Change the value of “region and instances”.

import boto3

region = 'eu-west-3'

instances = ['i-05be5c0c4039881ed']

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

def lambda_handler(event, context):

#    ec2.stop_instances(InstanceIds=instances)

    ec2.start_instances(InstanceIds=instances)

    print('stopped your instances: '   str(instances))

Save the function

Note: Be careful while writing Python code, it may give errors if the indentation is not proper.

Click on “Test” to execute the function. 

See the details of the execution and you can clearly see that the function was successfully executed. This means the Lambda function has triggered a request to start the instance. 

Here, you can see that the Instance State is “Initializing” which means the Lambda function has successfully processed our request to start the required instance.

Conclusion:

In this article, we saw how to create a simple Lambda function to stop ec2 instance, assign required policies to the roles being used by the Lambda Function. We also saw how to start an EC2 instance using the Lambda function. We edited the same function to perform stop/start EC2 instance, you can create 2 different functions for this.