Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compute engine startup script can't execute as a non-root user

Boiling my issue down to the simplest case, I'm using Compute Engine with the following startup-script:

#! /bin/bash
sudo useradd -m drupal
su drupal
cd /home/drupal
touch test.txt

I can confirm the drupal user exists after this command, so does the test file. However I expect the owner of the test file to be 'drupal' (hence the su). However, when I use this as a startup script I can still confirm ROOT is the owner of the file:

ls -l result

meaning my

su drupal

did not work. sudo su drupal also does not make any difference. I'm using Google Container OS, but same happens on a Debian 8 image.

like image 950
Pega88 Avatar asked May 10 '17 18:05

Pega88


1 Answers

sudo su is not a command run within a shell -- it starts a new shell.

That new shell is no longer running your script, and the old shell that is running the script waits for the new one to exit before it continues.

The sudo su command will start a new shell. The old shell waits for the old one to exit and continues executing the rest of the code. Your script is running in the 'old' shell, which means these commands:

cd /home/drupal
touch test.txt

are still executed as root and thus the owner of these files is root as well.

You can modify your script to this:

#! /bin/bash
sudo useradd -m drupal
sudo -u drupal bash -c 'cd ~/; touch text2.txt'

and it should work. The -u flag executes the command as the user specified, in this case 'drupal'

like image 187
Serge Hendrickx Avatar answered Sep 25 '22 19:09

Serge Hendrickx