Schedule Daily EC2 instance stop using CloudWatch Events

Purpose

Infra/Dev-ops team do have instance created for POC/Demo/testing purpose which we need to stop daily (office off-hours) or during weekends for cost saving purpose. As this adds an overhead for us to daily stop the instance manually before leaving office and sometimes we might forget to stop the instance which again will add up the cost.So there was a demand to automate this process in order to save cost.

Solution

Now we have a feature in AWS to schedule a job in CloudWatch Events to stop a running instance daily or during weekend which is used for POC/Demo/testing purpose without any manual intervention.

Use-case

I have to schedule it for one of my POC “poc_rundeck” instance to stop automatically daily during office off hours say after 9pm IST which will help us in saving cost .

Step One—Create a Rule

click on “create role” in CloudWatch Events Rules

CW1

Step Two—Schedule a Cron inside Rule

Select Schedule

CW2

Set Cron expression to ” 30 15 * * ? * ” , In this use case we have set it to 15:30 GMT which is 9:00 PM IST . Link about CloudWatch Events schedules.

CW3

Step Three – Add Targets

Click “Add target”

CW4

Select “Built-in target”

CW5

Set Action as “Stop an EC2 instance”

CW6

Select the instance ID of machine to stop

CW16

Add another Target “SNS topic” for email Notification

CW7

Set the Topic to which you wish to send notification, In this use-case we select “infra”

CW8

Step 4 —Configure Details

CW9

Enter name and description and set State to Enabled as shown.

CW10

Give AWS Permissions by either creating a new role or selecting the existing role as shown.

CW11

Click “create rule” to complete the configuration step.

CW10

You will see a new rule created “rundeck_stop” and schedule in Rules dashboard

CW13

Detail View of Rule created

CW14

“poc-rundeck” Instance gets stop automatically at 9 pm IST

CW15

If you plan to work late night in office on your POC instance you can disable the rule by editing it in order to avoid instance getting stopped by CloudWatch events.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s