'passing user-data as a string to aws cli ec2 run-instance command

I am trying to provide bash command for bootstrapping my ec2 instance during creation time in the following way

aws ec2 run-instances --image-id ami-0000025f7c02a13b2 --count 1 --instance-type t2.micro --user-data '#!/bin/bash\nyum install git -y'

I can spin up the ec2 but I cannot get the bash script to work. In the logs I see the following

/bin/bash\nyum: bad interpreter: No such file or directory

which makes me feel like the string is formatted wrong.



Solution 1:[1]

Try adding a $ in front of your user data string.

aws ec2 run-instances --image-id ami-0000025f7c02a13b2 --count 1 --instance-type t2.micro --user-data $'#!/bin/bash\nyum install git -y'

Solution 2:[2]

If you intend to load a long script, it would be better to load the script from a file like this:

aws ec2 run-instances --image-id ami-abcd1234 --count 1 --instance-type m3.medium \
--key-name my-key-pair --subnet-id subnet-abcd1234 --security-group-ids sg-abcd1234 \
--user-data file://my_script.txt

and you file should be like this:

#!/bin/bash
yum update -y
service httpd start
chkconfig httpd on

See more details about loading data from a file while working with aws cli from this link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jellycsc
Solution 2 Amado Saladino