#!/bin/bash -exu # The shebang line is here in case there's is currently an empty user-data script. # It wont hurt if already there. ################## # auto_terminate.sh script # When creating an AMI, a aws ec2 create-image command is added to the end of # the user-data script. Creating AMIs prevent the script going any further. # # To get around this the this is script is added before that happens. # # https://stackoverflow.com/questions/27920806/how-to-avoid-heredoc-expanding-variables cat >/root/terminate-myself.sh << 'EOL' #!/bin/bash -exu # install jq dependencies function install_jq() { if ! type jq > /dev/null ; then wget "https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64" mv jq-linux64 /usr/local/bin/jq chmod a+x /usr/local/bin/jq fi } function configure_aws_cli() { local home_dir=$1 # Configure aws cli in case it is not yet configured mkdir -p $home_dir/.aws if [ ! -f $home_dir/.aws/config ]; then EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone` EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`" cat >$home_dir/.aws/config < /etc/rc.d/rc.local.tmp mv /etc/rc.d/rc.local.tmp /etc/rc.d/rc.local if [ -n "$SPOT_INSTANCE_REQUEST_ID" ]; then cancel_spot_request fi terminate_instance EOL chmod a+x /root/terminate-myself.sh <% if @options[:auto_terminate] %> <% if @options[:ami_name] %> # schedule termination upon reboot chmod +x /etc/rc.d/rc.local echo "/root/terminate-myself.sh <%= @options[:ami_name] %> >> /var/log/terminate-myself.log 2>&1" >> /etc/rc.d/rc.local <% else %> # terminate immediately /root/terminate-myself.sh NO-WAIT >> /var/log/terminate-myself.log 2>&1 <% end %> <% end %>