← All Posts

Easily Rerun EC2 UserData

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.