DEV Community

Zahraa Jawad
Zahraa Jawad

Posted on

AWS Lambda function and CloudWatch to schedule for start and stop of the server-EC2 instance Part-1

Introduction

look at how we can start and stop our ec2 on aws at a fixed interval so what s the requirement, the requirement is that let's say you have a staging server or a test server that you want to use during a fixed time, for example during my office hours I would want my staging instance to be running but then once the office hour stop I mean end's right let's say around 5:30 or maybe let's keep a little bit of buffer and say at nine o'clock its right we will shut down the instance because then after that for quite some time it is not required so we will be saving money when the instance is stopped so what is the best idea to do that now I don't really want to every day go and stop the instance it should be done automatically, so in this article, I will show script or rather a lambda function which will help as do this particular.

AWS Lambda Function

AWS Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code on a high availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, and logging. With Lambda, you can run code for virtually any type of application or backend service. All you need to do is supply your code in one of the languages that Lambda supports.

Image description

The uses of Lambda

Lambda is one of the computing services, that is ideal for many application scenarios, allowing you to run application code using the standard Lambda runtime environment and within the resources provided by Lambda. , you can use Lambda with many of AWS services:

  • File processing: Use Amazon Simple Storage Service (Amazon S3) to trigger Lambda data processing in real time after an upload.

  • Stream processing: Use Lambda and Amazon Kinesis to process real-time streaming data for application activity tracking, transaction order processing, clickstream analysis, data cleansing, log filtering, indexing, social media analysis, Internet of Things (IoT) device data telemetry, and metering.

  • Web applications: Combine Lambda with other AWS services to build powerful web applications that automatically scale up and down and run in a highly available configuration across multiple data centers.

  • IoT backends: Build serverless backends using Lambda to handle web, mobile, IoT, and third-party API requests.

  • Mobile backends: Build backends using Lambda and Amazon API Gateway to authenticate and process API requests. Use AWS Amplify to easily integrate your backend with your iOS, Android, Web, and React Native frontends.

To start and stop EC2 from Lambda function:

One of the uses of lambda is to start and stop the instance, and this is done by running the code for that in the lambda function, through some of the following steps:

• Create a custom AWS Identity and Access Management (IAM) policy
and implementation role for your Lambda function.
• Create Lambda functions that stop and start your EC2 instances.
• Test your Lambda functions.

Now let's implement the steps to start and stop the instance through the lambda function code:

Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
EC2 is already created, so the next step we will do before creating the lambda function is to create an IAM role, so to do this go to the AWS management console and then find IAM in services, and click on IAM .

Image description

We need to create a role for lambda and attach the role to the lambda function and the role that we can attach to the ec2 instance as well .

  • Click on the role in the left navigation pane.
  • Click on the create role

Image description

  • Select the AWS service.
  • Choose Lambda.
  • Then click on Next.

Image description

  • We need to add Permissions policies, select the AdministorAccess and then click on Next.

Image description

Note: Because we need to start and stop instance it is recommended that we go only with start and stop permissions.

  • Give a name of the role, then click on Create role.

Image description

Attach policy to our role to start and stop instant:

  • Choose the role we created.

Image description

  • Click on Add permissions then choose Attach policy.

Image description

  • Click on Create policy.

Image description

  • Here we create policy by the Visual editor:

Image description

1- In services: search on EC2 service and select it.

Image description

2- *In Action *:search on (start instances),(stop instances) and choose them by click in the check box, then click on close.

Image description

3- In Resources: click on Add ARN.

Image description

  • After all, click on Next: Tags

Image description

  • Click on Next: Review

Image description

Give name to the policy, then click on Create policy

Image description

  • The policy is created .
  • Choose the policy that created and click on Action then Attach( to attach policy to role) .

Image description

  • Choose the role you need to attach policy, then click on Attach policy.

Image description

Now to Create Lambda functions that stop and start your EC2 instances:
-In the search engine we type lambda , then choose Lambda.

Image description

1. In the Lambda console, choose Create function.

Image description

2. Choose Author from scratch.

Image description

3. Under Basic information, add the following:
- For Function name: enter a name that identifies it as the function used to start your EC2 instances.

Image description

- For Runtime: here choose Python 3.9.

Image description

- Under Permissions: expand Change default execution role.
- Under Execution role: choose Use an existing role, then choose the IAM role that you created.

Image description

- Our lambda function is Successfully created.

Image description

From AWS documentation of stop and start Amazon EC2 instances at regular intervals using Lambda:

https://aws.amazon.com/premiumsupport/knowledge-center/start-stoplambda-eventbridge/

Image description

Under Code, Code source, copy and paste the previous code into the editor pane in the code editor ( lambda_function). This code stop (or change to start) the EC2 instances that you identify. Example function code-stopping (or starting) EC2 instances.

Test Lambda functions:

When past the code into the editor pane in the code editor (** lambda_function), make some change:
**- In region:
enter the region of your instance.
- In instance: enter the id of instance.
- Specify the stop or start of instance.
- Then In the Code source section, select Test.

In the Configure test event dialog box, choose Create new event.

  • Enter an Event name. Image description

Image description

Image description

To ensure that the code is executed successfully:
We go to the instance and it's a stopped state,

Image description
do a refresh, and notice that the instance is running

Image description

  • We can repeat the same steps to stop the instance by change code to stop.

-In the next part of this work, we'll automate starting and stopping the instance by scheduling it with AWS CloudeWatch services.

References:

1- https://docs.aws.amazon.com/lambda/latest/dg/welcome.html
2- https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambdaeventbridge/

Top comments (0)