AWS have released a new featue called CloudWatch Events, which lets you configure events fired by cloudwatch and direct them to SNS, Lambda functions, etc. Here's the blog post
Here's the motivational image:
The set of supported events sources is still somewhat limited, but this is way better than polling, which is what we had to do up until now...
In this gist you'll learn how to create such event and post updates to slack whenever an EC2 instance changes state (e.g. starting, terminating etc) You may of course use similar events to send SNS notofications to emails or anything else of that sort (in case you don't want slack)
- Create a slack incoming webhook and get your token
- Encrypt this token with KMS and paste the CiphertextBlob at 'Replace with your KMS token' (KMS encryption is a bonus, not required, you may just use the token plaintext)
Example how to encrypt: (replace
22e06448-f73c-42c4-b18f-74f91eb7bc1a
with your own key-id from KMS - create a new key and copy the ID)
$ aws kms encrypt --key-id 22e06448-f73c-42c4-b18f-74f91eb7bc1a --plaintext "your slack token"
{
"KeyId": "arn:aws:kms:us-west-2:xxxxxxxxxx:key/22e06448-f73c-42c4-b18f-74f91eb7bc1a",
"CiphertextBlob": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
}
- Create a Lambda function and replace all the const at tge header of the file with your personal data Function name: cloudwatch-event-to-slack You may use the attached test data to test this function (right after you finish the next item)
- Give your function's role permission for the kms:Decrypt action. (assuming you're using KMS) Example:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:Decrypt"
],
"Resource": [
"<your KMS key ARN>"
]
}
]
}
- Add the following permission to the same IAM role as before in order to allow describing EC2 instnaces:
{
"Effect": "Allow",
"Action": "ec2:Describe*",
"Resource": "*"
}
- Create a new CloudWatch Event Rule to send EC2 events to this lambda function Screenshot: http://jmp.sh/uBi6dV8
- You may test this by terminating and lanching an EC2 instance.
Example output on Slack:
aws.ec2 (us-west-2): i-531a188a is shutting-down
- Prosper
how can I create a lambda that recive information from CloudWatch events, change the instance Id for the instance name and then send it to sns service?