This week I will talk about CloudWatch Events, a new great feature what allows us to track events, define rules and take actions. Jeff already wrote post about it here and you can find the details of it. Today I’ll show a sample code that uses this feature.
Basically our scenario is; we create a new EC2 instance that has ‘Production’ tag. (Think of that we launch new production instances to be added our fleet). If, somehow, termination protection is not enabled, we’ll make it happen automatically. So our event source will be “EC2 Instance state change notification” and the state is “pending”. And for the target, we’ll use a Lambda function that checks for the instance’s tag , and if “Production” is found, checks the termination protection status. If status is “disabled”, then it enables it.
First of all, I create my lambda function and use the code below.
from __future__ import print_function from boto3 import Session def lambda_handler(event, context): session = Session(region_name='eu-west-1') ec = session.client('ec2') reservations = ec.describe_instances()['Reservations'] instances = sum( [ [i for i in r['Instances']] for r in reservations ], ) for instance in instances: id=instance['InstanceId'] for tag in instance['Tags']: for key, value in tag.items(): if 'Production' in value: print("Found an instance with 'Production' tag. Checking termination protection value of the instance with id:",instance['InstanceId']) terminate_protection=ec.describe_instance_attribute( InstanceId = id, Attribute = 'disableApiTermination' ) protection_value=(terminate_protection['DisableApiTermination']['Value']) if protection_value == False: print("Instance termination protection was '",protection_value,"', enabling it...") modify=ec.modify_instance_attribute( InstanceId = id, Attribute = 'disableApiTermination', Value='True', ) if(modify['ResponseMetadata']['HTTPStatusCode']==200): print("Enabled, your instance is now safe!") else: print("Good job, it is already enabled!")
Then I create my rule. I select “pending” state and select my “Check_Termination_Protection” lambda function.
I configure the rule’s details and create it.
And my rule is successfully created.
Now I create 2 instances and tag them using “Production” tag.
My instances are now in pending state.
Their termination protections are “False” for now.
This event invoked our lambda function and it successfully enabled the termination protection for the instances.
We can also check the console and see the status of termination protection.
So this was the basic usage example of CloudWatch Events. We were able to protect our production instances from being terminated using CloudWatch Events. I hope as AWS add new event sources and targets, things will be much more funny!
I hope you find it useful. If you have any question or comment, please feel free to write and don’t forget to share please.