Turn on and off your AWS resources using the Cloud Custodian

Automatically turn on and off your AWS EC2 instances

Cloud Custodian is an open-source tool from Capital One written in python language and comprises of many tools and scripts. It is a powerful tool that allows you to put guard rails in real-time. It is serverless (code runs as a lambda function) and no agent is required. It allows you to define your own rules. It is also referred to as a “Policy as Code”.

In this story, we will discuss how awesome is the Cloud Custodian that helps us save money. It automatically turns off the ec2 instances every night or weekend and turns them back on every morning. In the below example, we have discussed a few scenarios-

# 1 — EC2 off-hours stop

policies:- name: csp-na-ec2-off-hours-stop
resource: aws.ec2
comments: |
The policy will apply only to those EC2 instances that are
atleast 1 hours old and include the tag "c7n_off_hours". Tag
your EC2 instance with Key "c7n_off_hours" for Custodian to
consider it in scope for action. Value can be anything.
Custodian just look for "Key" to consider it into the scope for
offhours. Stop EC2 instances as per schedule in c7n_off_hours
that is 0 UTC = 6PM CST.
filters:
- "tag:c7n_do_not_shut_down": absent
- "tag:aws:autoscaling:groupName": absent
- type: offhour
default_tz: "utc"
offhour: 0
tag: c7n_off_hours # Use this tag to be included in scope
- type: instance-age
hours: 1
mode:
type: periodic
schedule: "rate(60 minutes)"
execution-options:
output_dir: s3://bucket-name/cclogs/{{policy}}/
action:
- stop

#2 — EC2 off-hours start

policies:- name: csp-na-ec2-off-hours-start
resource: aws.ec2
comments: |
Tag your EC2 with Key "c7n_off_hours" for Custodian to consider
it in scope for action. Value can be anything. Custodian just
look for "Key" to consider it into the scope for offhours. Start
EC2 instances as per schedule in c7n_off_hours that is 12 UTC =
6AM CST.
filters:
- "tag:c7n_do_not_shut_down": absent
- "tag:aws:autoscaling:groupName": absent
- type: onhour
default_tz: "utc"
onhour: 12
tag…

--

--

Aakif Shaikh, CISSP, CEH, CHFI, CISA, GWAPT

Over 18 years of experience in a wide variety of technical domains within information security including information assurance, compliance, and risk management.