EC2 and Automatic Scripts at Launch - Amazon Linux AMIs

This topic leans more towards sysadmin duties more so than web development: Automatic Scripts at EC2 launch. Or as Amazon calls it, "User Data".

Whenever you launch an EC2 instance, you have the option to pass a script as user data to automate certain tasks. This works for both for select Linux and Windows AMI's, though Windows is run through power shell. As a web developer, this is extremely useful to me. I can launch an instance that automatically installs the LAMP stack and other utilities I need. I can only imagine how useful this would be for deployment at scale.

Let's get into the details - when you log into the Amazon console and start an EC2 instance, Step 3 at "Configure Instance" there is an option under "Advanced Details" to insert your own script.

Below is part of a script I wrote that installs part of the LAMP stack and git.

#!/bin/bash
# Update Packages
yum update -y

# Install Mysql, httpd, php, and git
yum install -y httpd24 php70 php70-mysqlnd git

# Start HTTP Server
service httpd start

# Set Permissions for Web Server
usermod -a -G apache ec2-user
chown -R ec2-user:apache /var/www
chmod 2775 /var/www
find /var/www -type d -exec sudo chmod 2775 {} \;
find /var/www -type f -exec sudo chmod 0664 {} \;

# Set PHP Info for debug
echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php

Now if I go to my instance's IP address (assuming that I used a security group with port 80 open) I should the apache test page. Cool, right?

What if I wanted it to send a push notification to my phone when the user data script is finished executing, and the instance is ready to go?

This is very complicated and I will go into more detail on another entry, but for now, here are the basic steps.

  1. Sign up for a pushbullet account. Install it to your phone, and get an API key.
  2. Create a topic within Amazon SNS (take note of the region)
  3. Subscribe a lambda function to that topic. The lambda function should send a request to the pushbullet API with your SNS subject and message. Hint from Letswp.io
  4. Create an EC2 Role that has access to SNS. When you launch the instance, assign it that role.
  5. Use the below code at the end of your user data script. Take note to replace the AWS Region and the Topic ARN.
aws configure set default.region aws-region-here
aws sns publish --topic-arn arn:aws:sns:aws-region-here:ID:SNSTopicName --message "Linux Server Setup Complete" --subject "Linux server has been set up. Script executed."

If you did everything correctly by following the above steps and inputting into user data the script above, you should receive a notification when the instance has launched.