Home / How To / AWS Lambda function to start and stop an EC2 instance

AWS Lambda function to start and stop an EC2 instance



Lambda is covered by the "Compute" service of AWS (Amazon Web Services). With Lambda we can encode without providing or managing servers. Lambda automatically runs our code without requiring us to provide or manage servers. We just need to write the code and upload it to the Lambda function.

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

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

What we need to provide is just the code and AWS Lambda takes care of maintenance, automatic scaling, high availability. This code can also be run in response to events. To use Lambda, we must write the code in one of the languages ​​it provides.

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

Requirements

  1. AWS Account ( Create if you do not 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. Change IAM role
  4. Perform the role

Log in to AWS

  1. Click here to go to AWS login page.

When we click the link above, we see a web page as follows where we have to log in using our login credentials.

  AWS Log in

When we have successfully logged in to AWS we will see the main console with all services listed as follows.

  AWS Management Console

Creating a Lambda Function

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

Click the arrow near the default region (Here it is Paris) and you will see a list of available regions and select the desired region. Here I have chosen "Paris", it remained unchanged. You can choose according to your choice or requirements.

  Creating a Lambda Function

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

  Lamda

You will get a screen where you can create a Lambda function. Click "Create function"

  Create function

You can either create a function on your own, use the existing drawings or browse an archive where we can search for the desired function to see if it exists. Here we create our own simple Lambda function with Python.

Click "Author from Scratch" to write our own Lambda function.

Enter a name for the function.

Select "Python 3.6" from the list box with Runtime.

  Select Python runtime

The Lambda function must have sufficient permissions for its run. Select "Create a new role with basic Lambda permissions". This creates a new role with the same name as Function Name with any random key as a suffix.

  Configure permissions

The above default permissions are not enough. We will understand this better in the next step. For the moment, we will only create one function and see what possible errors may occur.

Add the following code to the function and click "Save" to save the function.

Change the value of "region and instance" ".

  import boto3 
region = & # 39; eu-west-3 & # 39;
instances = [' i-05be5c0c4039881ed & # 39;]
ec2 = boto3.client (& # 39; ec2 & # 39 ;, region_name = region)
def lambda_handler (event, context):
ec2.stop_instances (InstanceIds = instances)
print (& # 39; stopped your instances: & # 39; + str (instances))

  Lambda function in AWS [19659053] Feature Code

Click the "Select a test event" button except the "Test" button and select "Configure Test Event". The following screen appears. Do not make any changes and just name the event, here it is "testStopEC2" and click "Save". This event is just one example of events and has no relevance to our function. We can create another event according to our requirements.

  Configure test event

Note: We can create a Cloudwatch event with which we can trigger this Lambda function based on the event triggered in Cloudwatch. We will not discuss this now, as a clear understanding of Cloudwatch is required. So we continue with a simple event. You can explore this when you get to know Lambda and Cloudwatch.

Now click on "Test". Please note carefully, the function has not worked due to insufficient condition. This is what I talked about in the previous step. Don't panic when you look at the error. We assign the necessary permissions for the role created in the creation of the Lambda function.

  Test Lamda Function

Change IAM Role

Click "Services" at the top right of the screen and search for IAM.

  IAM service

You will see a screen as follows. This is the main screen for IAM. We will not go into detail on IAM in this article.

  AWS IAM

Click "Roles" from the left panel and click on the role that starts with the same name as the Lambda function name and has some random string to add to it.

  Roles

Click "Attach Policies"

  Attach Policies

Search for "ec2" in the search box and select "AmazonEC2FullAccess" from the list and click the "Attach Policy" button. Now we are all set to perform the Lambda function with the necessary permissions.

  Attach policy

Perform the Lambda function

Return to our Lambda function and now click on the "Test" button. This time you can see in the logs This means that the Lambda function has triggered a request to stop the instance.

  Run the Lambda function

Go to the "EC2" service and see if the instance with the instance ID we gave The Lambda function has been stopped or not. Here you can see that the instance state "stops" which means that the Lambda function has successfully processed our request to stop the required instance.

  launch Instance

In the previous steps we saw a Lambda function to stop the EC2 instance. Now let's see how the EC2 instance can be started with Lambda. To do so, you can either edit the same function or write a new function according to the same previous step.

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

  Start Instance Function

Use the following code to start EC2 instance with Lambda.

Change the value of "region and instance".

  import boto3 
region = & # 39; eu-west-3 & # 39;
instances = [ & # 39 ; i-05be5c0c4039881ed & # 39; ]
ec2 = boto3.client (& # 39; ec2 & # 39;, region name = region)
def lambda_handler (event, context) :
# ec2.stop_instances (InstanceIds = instances)
ec2.start_instances (InstanceIds = instances)
print (& # 39; stopped your instances: & # 39; + str (instances))

Save function

Note : Be careful when writing Python code, it may cause errors if the retraction is not correct.

  Function code

Click "Test" to perform the function.

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

  Performs the Lamda function

Here you can see that the instance state "Initiates" which means that the Lambda function has successfully processed our request to start the necessary instance.

Conclusion:

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


Source link