EC2 UserData code blocks only run when an EC2 starts up for the first time by default. Rerunning this code can be useful for troubleshooting purposes. However, the way to do this is not very straight forward. Let's go through how to view, verify, and execute your EC2's UserData.
First, we must log into our EC2 using SSH and our .pem file.
> ssh -i "my-cert.pem" ec2-user@my.machine.ip
This article will not go into the details of how to SSH into a machine, you can learn how to do this from the AWS Documentation.
Next, we must elevate to the root user.
> sudo -i
An EC2's UserData can be accessed at the url: http://instance-data/latest/user-data
, so we can use curl to redirect this to a file in order to inspect it.
> curl http://instance-data/latest/user-data > user-data.sh
We can then inspect the file using cat
or vim
.
> cat ./user-data.sh
We can then modify the permissions and execute it.
> chmod +x user-data.sh
> ./user-data.sh
Other Variations
We can run the script in one single command if we don't want to inspect it first by piping it directly.
> curl http://instance-data/latest/user-data | sh
Another option is if you'd like to see each line written to STDOUT as it runs, we can enable this by adding set -ex
to the top of our user-data.sh
script before executing it.
Top comments (2)
No need to
curl
, the userData content is stored under/var/lib/cloud/instances/
. Depending how you structured your userData (e.g., if you only had a simple#!/bin/bash
), the immediately-executable script content will be stored in/var/lib/cloud/instances/scripts/part-001
. Meaning all you really need to do to re-run it is SSH into the host and dosudo bash var/lib/cloud/instances/scripts/part-001
.Things get a bit more complex if you've used multipart-MIME userData, but the underlying logic is similar.
Similarly, if you want to reboot your instance and have it rerun userData automatically, simply
rm -rf var/lib/cloud/instances/<INSTANCE_ID>
Good stuff, thanks!