When you launch an instance in Amazon EC2, you have the option of passing user data to the instance that can be used to perform common automated configuration tasks and even run scripts after the instance starts. You can pass two types of user data to Amazon EC2: shell scripts and cloud-init directives.
How It Works
To enable the Shut down script, an agent must be installed on the instance during start up. This is done via the user-data entry and will have the agent up and running on the instance within a few seconds. Your shutdown script will be deployed to every new instance on your elastigroup. Our agent will sample the API for updates every 10 seconds to figure out if the script should run. Once we determine we are going to remove or replace the instance we will notify the agent so the script can execute. This means that the script will have around 10 minutes to execute prior to the instance beeing terminated.
Your instances will need access to the curl command in order for your shutdown scripts to function properly.
- Shutdown scripts must start with the #! characters and the path to the interpreter you want to read the script (commonly /bin/bash)
- Scripts entered as Shutdown scripts are executed as the root user, it is not necessary to use sudo in the script. Remember that any files you create will be owned by root; if you need non-root users to have file access, you should modify the permissions accordingly in the script. Also, because the script is not run interactively, you cannot include commands that require user feedback (such as rm without the -f flag).
- Adding the agent installation at boot time adds to the amount of time it takes to boot the instance. Please make sure the shutdown script installation code is the last step in your user-data. You should allow a few minutes of extra time for the tasks to complete before you test that the user script has finished successfully.
- It is recommended to adjust the draining time out for instances in the General Tab of the wizard under Advanced settings:
Navigate to the Compute Tab and open the Advanced settings
Install the Spotinst agent. For ease of use, we recommend adding this at the end of your user data script.
#!/usr/bin/env bash curl -fsSL http://s3.amazonaws.com/spotinst-labs/spotinst-agent/agent-init.sh | \ SPOTINST_TOKEN=<YOUR_API_TOKEN> \ bash
- , please get a token from https://console.spotinst.com/#/settings/tokens/permanent
Add your shell script to the shutdown script
#enter shutdown script here echo "Goodbye old instance"
/usr/bin/knife client delete -y -c /etc/chef/client.rb $ec2_instance_id