Introduction
Hello there! My name is Adam, an aspiring DevOps engineer who joined the Infrastructure team of Linkbal this year in February. My main focuses are optimizing the AWS environments and the server middleware. Occasionally I will make something cool and useful, most likely involving AWS, which I would like to share with you.
Today, I will be detailing how to schedule a security update script to be run on an EC2 Linux instance on a time schedule, then push the output logs to a Slack channel for everyone to see.
Objectives
First, let’s consider what we want to achieve, so as to determine what the end result should be:
- Automatically run security updates on an EC2 Linux instance on a pre-determined schedule.
- Be notified of the update and see the output in a Slack channel.
- Be able to change the time schedule or turn on/off without having to access the instance.
The 3rd point is important as it adds a layer of convenience to the method. If it ever becomes necessary to stop the updates, we want to be able to do so quickly and easily, without having to remove what we put in place.
Pre-requisites
- AWS account with privileges to create a CloudWatch rule and use Systems Manager.
- EC2 Linux-based instance with AWS CLI installed.
- IAM role attached to the EC2 instance.
- Permission to access the EC2 instance via SSH connection and use root credentials.
- A Slack account with a channel for receiving the output logs and the permission to create a webhook.
Plan and script
The source code originally came from here: Slack notification via curl
The diagram was drawn using a free account in LucidChart.[code] #!/bin/bash
# This script runs a security update then pushes the output to Slack.
VAR1=$(sudo yum update –security -y)
IP=$(curl ifconfig.me)
function post_to_slack () {
SLACK_MESSAGE="\`\`\`$1\`\`\`"
SLACK_URL={Slack web hook} # Replace this with your own web hook, without the braces
case "$2" in
INFO)
SLACK_ICON=’:slack:’
;;
WARNING)
SLACK_ICON=’:warning:’
;;
ERROR)
SLACK_ICON=’:bangbang:’
;;
*)
SLACK_ICON=’:slack:’
;;
esac
curl -X POST –data "payload={\"text\": \"${SLACK_ICON} ${SLACK_MESSAGE}\"}" ${SLACK_URL}
}
post_to_slack "Result of security update for $IP: $VAR1" "INFO"
exit 0
[/code]
Procedure
- Create a Slack web hook for the channel you want to receive the log output in. Paste the web hook into the script as the value for SLACK_URL (without the {} braces).
- Upload script to the instance (take a note of the path). This can be done from the command line as such:
$ scp -i /path/to/key.pem ec2-user@{IPv4 DNS}:path/to/file
Or you can SSH connect to the instance, make a new file and paste the code in there:
$ ssh -i /path/to/key.pem ec2-user@{IPv4 DNS}
$ vi /path/to/file/update_security.sh
It doesn’t matter were the file goes, so long as you know where it is.
Be sure to change the permissions on the script so that it can be executed.
$ chmod 775 /path/to/file/update_security.sh
Install the AWS SSM agent: (installed by default on AWS Linux 1 AMIs since 2017.9 and on all AWS Linux 2 AMIs)[Manually install SSM agent on Amazon EC2 Linux instances]
Add the policy “AmazonEC2RoleforSSM” policy to the role being use by the EC2 instance. - Go to CloudWatch, select “Rule” on the left toolbar and then “Create rule”. Set the time expression by either a fixed rate or a cron expression. Note that the time will be in UTC, so depending on your timezone you will need to adjust the hour and possible day values. As an example, to update at 2am UTC Monday-Friday, the expression would be:
0 2 ? * MON-FRI *
For help with cron expressions in AWS, please see: AWS CloudWatch – How to schedule events
Select “SSM Run Command”.
Select the document “AWS-RunShellScript (Linux)”
Target key = InstanceIds (can choose a different target, if you prefer)
Target values = {Instance ID} i.e. i-a1b2c3d4e5
Click on the “Configure parameters” drop down.
Commands = ./update_security.sh
WorkingDirectory = /path/to/file/
ExecutionTimeout = 100
Select “Create a new role for this specific resource”
Click on “Configure details”. Give it a name and a description. - The CloudWatch Rule uses AWS Systems Manager to call the SSM Agent which runs the script. The script will run the update, then pass the output to a post function which uses the Slack web hook to post the output in your channel.
Even if there are no updates due, the message will still be sent. - Success! You can customize the name and image of the web hook in the Slack settings menu.
Conclusion
We have now configured for security updates to run on the AWS EC2 Linux instance on a specific time schedule, with the result of the update being sent to a channel in Slack. The script can be turned on/off easily from the AWS console (or by the AWS CLI) and we can change the time schedule there as well.
Let us now consider the advantages and disadvantages of this method.
Advantages
- Quick and simple to set up.
- The script is reusable; can be used on most if not all Linux instances on AWS. Only the Slack web hook would have to be changed if a different channel was required, otherwise no need to edit the script.
- Only a basic understanding of AWS is required.
- Virtually zero cost.
Disadvantages
- CloudWatch rule must be stopped manually. Could set up a trigger with SMS and Lambda to stop the rule without the need for human intervention.
- Only works for Linux instances. Windows would require something different.
- Root privileges are required to set up (possibly avoidable with AWS Systems Manager).
- Would be easier to understand if more details concerning the instance were put into the script, such as the name tag. (Can use ec2-metadata to obtain a lot of this information, but tags are not included in this list. Could use AWS CLI to get the instance name tag.)
Overall we have achieved what we set out to do. There are ways we could improve the script, but for now this is more than suitable.
I hope you have enjoyed this post, it’s a simple start with many more things to come. See you next time!
References
- Source code: http://blog.pragbits.com/it/2015/02/09/slack-notifications-via-curl/
- LucidChart: https://www.lucidchart.com/
- AWS CloudWatch – How to schedule events: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html
- AWS EC2 – Manually install SSM Agent on AWS EC2 Linux instance: https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-manual-agent-install.html
- Manually install SSM agent on Amazon EC2 Linux instances : https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-manual-agent-install.html