Wednesday, October 27, 2021

[SOLVED] aws ec2 run-instances: script as the plain text is ignored

Issue

I'm trying to pass the script as the --user-data parameter. If the same is run through --user-data file://some_file.sh all works. Also, it works if launch instance through AWS GUI by adding user-data in the correspondent launch configuration box.

My CLI command is

aws ec2 run-instances --image-id ami-0cc0a36f626a4fdf5 --count 1 --instance-type t2.micro --key-name key_name --security-group-ids sg-00000000 --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=some_name}]" --output table --user-data "sudo touch /tmp/install.log && sudo chmod 777 /tmp/install.log && echo $(date) >> /tmp/install.log"

if the same run as a script, it's content formatted as below

#!/bin/bash
sudo touch /tmp/install.log
sudo chmod 777 /tmp/install.log
echo $(date) >> /tmp/install.log

Also, I'd like to mention that I tried to pass string in different formats like :

--user-data echo "some text"

--user-data "command_1\n command_2\n"

--user-data "command_1 && command_2"

--user-data "command_1; command_2;"

--user-data "#!/bin/bash; command_1; command_2;"

User-data after launch is seeing but not executed

$ curl -L http://169.254.169.254/latest/user-data/


Solution

The first line must start with #!.

Then, subsequent lines are executed. They must be separated by a proper newline. It looks like \n is not interpreted correctly.

From how to pass in the user-data when launching AWS instances using CLI:

$ aws ec2 run-instances --image-id ami-16d4986e --user-data '#!/bin/bash
> poweroff'

As an experiment, I put this at the end of the run-instances command:

aws ec2 run-instances ... --user-data '#!
echo bar >/tmp/foo
'

When I logged into the instance, I could see the /tmp/foo file.



Answered By - John Rotenstein