Skip to content

Instantly share code, notes, and snippets.

@Riebart
Created January 10, 2018 16:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Riebart/a9a27062c6dee1d65957effe8d6ae53c to your computer and use it in GitHub Desktop.
Save Riebart/a9a27062c6dee1d65957effe8d6ae53c to your computer and use it in GitHub Desktop.
EC2 user data for setting up an EC2 instance with SSM and deploying into an ECS cluster.
#!/bin/bash
# Install the SSM agent:
# Ref: https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-startup-linux.html
cd /tmp
sudo yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm
sudo start amazon-ssm-agent
echo ECS_CLUSTER="ECS_CLUSTER_NAME" >> /etc/ecs/ecs.config
export PATH=/usr/local/bin:$PATH
yum -y install jq
easy_install pip
pip install awscli
aws configure set default.region "ca-central-1"
cat <<EOF > /etc/init/spot-instance-termination-notice-handler.conf
description "Start spot instance termination handler monitoring script"
author "Amazon Web Services"
start on started ecs
script
echo $$ > /var/run/spot-instance-termination-notice-handler.pid
exec /usr/local/bin/spot-instance-termination-notice-handler.sh
end script
pre-start script
logger "[spot-instance-termination-notice-handler.sh]: spot instance termination
notice handler started"
end script
EOF
cat <<EOF > /usr/local/bin/spot-instance-termination-notice-handler.sh
#!/bin/bash
while sleep 5; do
if [ -z $(curl -Isf http://169.254.169.254/latest/meta-data/spot/termination-time)]; then
/bin/false
else
logger "[spot-instance-termination-notice-handler.sh]: spot instance termination notice detected"
STATUS=DRAINING
ECS_CLUSTER=$(curl -s http://localhost:51678/v1/metadata | jq .Cluster | tr -d '"')
CONTAINER_INSTANCE=$(curl -s http://localhost:51678/v1/metadata | jq .ContainerInstanceArn | tr -d '"')
logger "[spot-instance-termination-notice-handler.sh]: putting instance in state $STATUS"
/usr/local/bin/aws ecs update-container-instances-state --cluster $ECS_CLUSTER --container-instances $CONTAINER_INSTANCE --status $STATUS
logger "[spot-instance-termination-notice-handler.sh]: putting myself to sleep..."
sleep 120 # exit loop as instance expires in 120 secs after terminating notification
fi
done
EOF
chmod +x /usr/local/bin/spot-instance-termination-notice-handler.sh
@lotif
Copy link

lotif commented Apr 10, 2018

Thanks for posting this gist, very helpful! However, it didn't work for me right away. I had to escape all the dollar signs with \$ to avoid them from being evaluated instead of just written into the file. Thanks!

@pmcenery-bl
Copy link

An alternative to escaping the variables is to single quote the EOF like this:

cat << 'END' > /some/script.sh
export var="x"
echo $x
END

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment