[AWS] Lab: Lambda - build a Chaos monkey
Solution Outline
To run our function we use a service called CloudWatch, which periodically generates events. Those events are sent to the Lambda function, and on each event, the Lambda function gets a list of instances from the environment and will randomly terminate one of them. (see below the summary diagram)
You can find the code for this demo in the course repo: https://github.com/udacity/cloud-developer/tree/master/course-04/exercises/c4-demos-master/04-chaos-monkey
In the 04-chaos-monkey
directory install the dependencies:
npm install
and then zip the folder so that it can be uploaded.
zip -r chaos-monkey.zip .
Create a Lambda function
1. Create a empty Node.js v10.x lambda function
2. Upload
chaos-monkey.zip
Get some running EC2 instances
Following the post: Host a Static Webpage, running two EC2 instance with public HTTP access.
Create a CloudWatch Event
So every 1 min, it will trigger Lambda `chaos-monkey` function.
After 1 min, we can see that Function has been triggered but with error result:
We can fix this by add EC2's List and TerminateInstance policy to the Role.
Fix IAM policy
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "logs:CreateLogGroup", "Resource": "arn:aws:logs:us-east-1:645307551852:*" }, { "Effect": "Allow", "Action": [ "ec2:TerminateInstances", "ec2:DescribeInstances" ], "Resource": "*" } ] }
After that, it should work as expected. Every 1 min, cloudwatch will trigger a lambda function to turn off EC2 instances that are running. You can configure EC2 that it will automatcilly bring up again.