Developing Server less Skills (AWS)

Ghazanfar Ali
4 min readAug 30, 2023

--

Scenario:

This project involve python, lambda and cloud watch events, the goal of this project is to automate the stopping and starting of ec2 instances, in AWS we pay bills on number of hours we use the server like in many cases we only need to use ec2 instances for only working hours by running our servers 24 hours can cost huge bills, this project is all about the automating that running time of our EC2 servers.

We will create two lambda functions one to stop the instances and one to start the instances,

Lets start!

We will create lambda function in python which will start and stop the EC2 instances:

Use this code in this function which will start the EC2 instance:

Now create other function to stop the instances:

We have created two python functions in lambda:

Now we will create the cloud watch event that will triggers our python functions in lambda:

  • Open the AWS CloudWatch Management Console.
  • In the navigation pane, choose “Rules,” then “Create rule.”
  • Under “Event Source,” choose “Event Source Type” as “Schedule.”
  • Specify the fixed rate or cron expression that represents your desired schedule (e.g., cron(0 9–17 ? * MON-FRI *) for 9 AM to 5 PM on weekdays).
  • Under “Targets,” click “Add target,” and choose “Lambda function.”
  • Choose the “StartEC2Instances” Lambda function as the target.
  • Click “Configure details.”

First we will create the stop schedule, which will stop the instance:

Put these details in cron job, as we are stopping the instance daily at 2:00 pm:

Invoke the stop function at cloudwatch:

Cloudwatch will create role on your behalf, go in roles and attach ec2 full access policy to this role so that it would be able to start and stop the instance:

We created the two schedules one for start the instance and one for stop:

Now go to your both lambda functions → configuration→ permission section there will be the role for each function, copy the name of role and in IAM section add the ec2 full access policy to both roles:

Now wait for desired time, the cloud watch will trigger the lambda functions to stop and start the instances.

Check the logs in cloud watch it will have created new log stream and will generate all the logs there to start and stopping the instance:

It have stopped my both instances as we wanted, also check the logs:

Instances:

Thats all in this project!

--

--

Ghazanfar Ali
Ghazanfar Ali

Written by Ghazanfar Ali

I write technical blogs on DevOps and AWS, Azure and GCP

No responses yet