How can i re run user data on aws ec2 from the console?

6.2k views Asked by At

I would like to ask if there is a way to re-execute user data on a launched instance. I want to restart a service and to edit ~./ssh/autorized_keys.

I found information at https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/ but the cloud log from the console does not show anything to have changed.

2

There are 2 answers

0
Thomas On

AWS only run the user data at the first launch. You need do the following two things:

  1. use mime-multipart to append your new scripts. You could the command write-mime-multipart in cloud-utils to create the mime-multipart file. Please refer the Cloud-init if you need more details.
  2. use mime-multipart to set scripts-user run always. In /etc/cloud/cloud.cfg, refer Always run cloud-init scripts to see the options

So, you need copy all the scripts from the link your provided and replace the shell script part with yours. https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/

Content-Type: multipart/mixed; boundary="===============5940869395195845375=="
MIME-Version: 1.0

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

#cloud-config
cloud_final_modules:
- [scripts-user, always]

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

#!/bin/bash
/bin/echo "Hello World." >> /tmp/abcde
--===============5940869395195845375==
1
Clarius On

Did this using an SSH session. Took a copy of the user data as a script and reran it from the CL.

curl http://instance-data/latest/user-data > user-data.sh
chmod u+x user-data.sh
sudo ./user-data.sh

Just be sure that when you rerun the user-data.sh script that you edit out any commands you might not want to rerun.