I have already launched my Amazon EC2 instance, but I want to execute user data again. How can I do this?

As part of the metadata included with Amazon EC2 instances, user data can be used to install packages or scripts. By default user data is executed once, at the first boot of the instance.

There are situations that would benefit from the ability to execute user data a second time--for example, if the SSH private key is lost and you are unable to log in to the instance. Repairing the instance might involve either creating an AMI or attaching the volume to another instance to troubleshoot. There are situations where that would be the preferred method. However, an alternative method can be resolved with a few commands.

Note: Back up your data before proceeding further. For more information, see Best Practices for Amazon EC2.

The user data provided should be removed from the instance after the issue is resolved. We recommend considering the security implications of being able to run user data beyond the first boot of an instance. Modifying the user data of an instance is done through the ModifyInstanceAttribute API.

Note: IAM policies can be created to restrict this method.

  1. In the Amazon EC2 console, choose the instance, Actions, Instance State, and then choose Stop.
  2. Choose Actions, Instance Settings, and then choose View/Change User Data.
  3. The following example is a shell script that writes "Hello World" to a file in the /tmp directory. Copy and paste into the User Data field, and then choose Save.
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

- [scripts-user, always]

Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

/bin/echo "Hello World." >> /tmp/sdksdfjsdlf

Choose Actions, Instance State, and then choose Start.

After the cloud-init phase is complete, the user data commands that you've included should have executed on the instance.

Did this page help you? Yes | No

Back to the AWS Support Knowledge Center

Need help? Visit the AWS Support Center

Published: 2017-08-11