In the first part of the article, we manually launched an instance using the lambda function without going to the instance console. In this part, we will stop the EC2 instance and automatically stop and start the EC2 instance by setting a scheduler using AWS CloudWatch.
- We have one function that created previously to start EC2 instance (StartEC2Instance), and now to create another lambda function to stop the EC2 instance, click on create function.
1. Choose Author from scratch.
2. For Function name: enter a name that identifies it as the function used to stop your EC2 instances.
3. For Runtime: here choose Python 3.9.
4. Under Permissions: expand Change default execution role.
5. Under Execution role: choose Use an existing role, the choose the IAM role that you created.
6. Then click on Create function.
- Our lambda function for stop instance is Successfully created.
And again, from AWS documentation of stop and start Amazon EC2 instances at regular intervals using Lambda:
Under Code, Code source, copy and paste the code into the editor pane in the code editor ( lambda_function). This code stop the EC2 instances that you identify.
To ensure that the code is executed successfully:
We go to the instance and do a refresh, and notice that the instance is stopped.
- In CloudWatch, we notice that the log for the start and stop instance are recorded in log groups.
CloudWatch to Scheduling start and stop the instance:
We can automate the operation of start and stop instances by scheduling the time of start and stop the instance by the AWS CloudWatch and the events of the AWS lambda function, the CloudWatch rule can trigger multiple kinds of things based on certain rules or conditions and what we are going to use the CloudWatch rules for is to set up a cron at which a specific time will trigger a specific lambda function.
The steps of Scheduling:
- Click on the Rules in the left navigation pane. 2. click on Create rule.
3. Use the schedule option
4. Choose Cron expression .
5. Enter the time for start or (stope the server-instance).
6. Choose the target to invoke an event (here Lambda function
is our target).
7. Choose the lambda function.
8. Click on Configure details.
In the next step, to configure the rule details:
9. Give a name to the rule.
10. Give a description to the rule (optional).
11. Click on Create rule.
The rule for starting instance is successfully created.
And the instance will run at the time we specified.
like the same steps, we can make a schedule to stop instances by choosing the stop instance event of the lambda function.
The rule for stopping instance is successfully created.
And the instance will stop at the time we specified.
Top comments (0)