How to run a script when running AWS Cloud Formation as another user?

I am having trouble starting an AWS Ubuntu instance (from the Cloud Formation template) and successfully running the script on startup. This script is executed, but I do not want it to work as root. I want the script to be called as another user or when the script is run for the script to change the user.

Since we are trying to use Cloud Formation, I need to put a script or script link in my template file. The relevant part of my template file is shown below. The script 'myScript.sh' runs, but always as root.

"MyImage" : { "Type" : "AWS::EC2::Instance", "Properties" : { "ImageId" : "xxxxxx", "KeyName" : "xxxxxx", "SecurityGroups" : [ "xxxxxx" ], "UserData" : {"Fn::Base64" : {"Fn::Join" : ["", [ "#include\n", "https://s3-eu-west-1.amazonaws.com/aFolder/myScript.sh \n" ] ] } } } } }, 

From the URL: http://alestic.com/2009/06/ec2-user-data-scripts it is said that these scripts always run as root. So instead, I decided to change the script to change the user. Below is an example script that does not do what I want. I commented this inline to explain what each step does:

 #!/bin/bash whoami > /home/ubuntu/who1.txt # Always returns 'root' su ubuntu # Appears to have no effect. Ubuntu user does exist whoami > /home/ubuntu/who2.txt # Always returns 'root' su ubuntu echo fish > /home/ubuntu/aFile.txt # File is not created sudo -u ubuntu bash # Appears to have no effect whoami > /home/ubuntu/who3.txt # Always returns 'root' 

I assume that there is something fundamentally wrong in my script, but I just can't see it! Does anyone have experience with AWS and Cloud Formation, and were you able to run the script as root? I really do not want the script to work as root, since the actions that will be run should not be at the root level.

Thanks Phil

+4
source share
2 answers

su does not change the user for the rest of the script, it launches a new interactive shell for the user you specify. In a non-interactive context such as your script here, this shell immediately exits due to the fact that there is nothing to do.

See this question for some suggestions on how to change the user for a number of commands. Alternatively, for individual commands, you can do sudo -u ubuntu [...] .

+8
source

This is a good alternative.

 #!/bin/bash su ubuntu << 'EOF' whoami >> /home/ubuntu/user_data_output2 EOF su user2 << 'EOF' whoami >> /home/user2/user_data_output2 EOF 

Why? This will cause the directory and environments to switch between commands in each EOF block.

eg:

 #!/bin/bash su ubuntu << 'EOF' cd /home/ubuntu/myfolder pwd # The result will be /home/ubuntu/myfolder # EOF 
0
source

Source: https://habr.com/ru/post/1482546/


All Articles