Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS EC2 instance user data bash script not working

I have an EC2 instance that I'm starting a very simple user data script:

#!/bin/bash
aws s3 cp s3://<bucket-name>/myconf.conf /etc/httpd/conf.d/myconf.conf

The instance has an associated IAM Role that allows access to the bucket and if I ssh into the running instance manually I can sudo execute the command to copy the file from S3 to the local filesystem.

However, if I delete the file, stop the instance, add the user data and start the instance again - then the file hasn't been copied down from S3 when I log back in.

Any ideas?

Thanks

like image 457
Nick Roper Avatar asked Mar 19 '26 02:03

Nick Roper


1 Answers

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.

Resolution

  • In the Amazon EC2 console, choose the instance, Actions, Instance State, and then choose Stop.
  • Choose Actions, Instance Settings, and then choose View/Change User Data.
  • 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"

#cloud-config
cloud_final_modules:
- [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/bash
/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.

like image 180
Sohail Ashraf Avatar answered Mar 22 '26 02:03

Sohail Ashraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!