AWS Lambda function and CloudWatch to schedule for start and stop of the server-EC2 instance Part-1
Tags: aws, cloudnative, community, awscommunitybuilder
Published: 2023-01-05 17:52:12

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzmpv6f2wzld8ha7r2ud.png)



**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jxqkym3ta7jsgr6rxni6.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xeebsz774v7s7a7zdsle.png)


- Select the **AWS service**.
- Choose **Lambda**.
- Then click on **Next**.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxxx190o7k70wp911ryz.png)


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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zr87oe92rnoisrg9cr2.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vg76aowaj5kas0ti4awc.png)

Attach policy to our role to start and stop instant:
- Choose the role we created.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q88yvy9pc1jn1uhfcvjr.png)

- Click on **Add permissions** then choose **Attach policy**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kdic7wrq4kmks4qu5sz9.png)

- Click on **Create policy**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gpahgeckzag2g3gel4fn.png)

- Here we create policy by the Visual editor:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8kh4gnon1sjsjym8t3m.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mroy1ym2epurpd1crt9v.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mtl823210axd2n5zbykf.png)

3- **In Resources:** click on **Add ARN**.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5j5btrxje0lphdho0kjm.png)

- After all, click on **Next: Tags**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7givd0j1omvryp3k3vo.png)

- Click on **Next: Review**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdhsb6cskr5zbsouahtk.png)

 Give name to the policy, then click on **Create policy**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oc2daa1ug0gl9x4lst1t.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5aa7yg5absfjocedu8mp.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f30kj6e7ys7pqhum6rz7.png)


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/enh20oalik8jepzz9yym.png)

**1.** In the Lambda console, choose **Create function**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fypnmc9an6g0zsol5y0.png)

**2.** Choose **Author from scratch**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdmvmdpapxnjxrgdb5p0.png)

**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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gcdda5cbsd64v6cxzqf7.png)

**-** For **Runtime**: here choose Python 3.9.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a7z2la3wfrr3l9i9w0gw.png)

**-** **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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sxnqax3ozugjfcrz56bc.png)

**-** Our lambda function is Successfully created.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmeoqiwaijduefszwb9e.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mk8r03ahn3doc0un56gu.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvn7jy0nmyxrzs4ola0o.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2hq2gu82yht3kq88oa9.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xc5w4d5o1830w3a5ytu.png)

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pwb3ju3j36b5kasdvk68.png)
do a refresh, and notice that the instance is running

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4bje9ozpxl5py8rg5o6.png)

- 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/