0

When creating an ec2 instance I use a bootstrap script. On the instance I install and configure an nginx web server. For security reasons, I need to create a new user (www-data).

The www-data user is created using:

sudo groupadd www-data
sudo adduser www-data -g www-data
sudo passwd -d www-data

Additional I run some python scripts on that machine. For this I used virtualenv. I run the following flow:

su www-data
pip install --user virtualenv 
python -m virtualenv $VIRTUALENV_NAME
cd /path/to/bin
source activate
pip install `stuff`
deactivate

My problem occurs after the above flow when I want to return to ec2-user. In the terminal typing exit does the job. Inside the bootstrap script it will exit the script.

I've tried with su ec2-user but it asks for password. I don't have one.

How to return to ec2-user from another user? Or how to workaround it

1 Answer 1

1

When you type this

su www-data
whatever
something-else
exit

su starts an additional shell as www-data user. Then you type consecutive commands, they are executed in this shell, so exit brings you back to the old shell.

If these commands are in a script, whatever won't be executed in the additional shell. The original shell will wait for su to exit before it goes to whatever and further. If you run such a script (a file like script.sh with proper shebang) from terminal, you'll be taken to an interactive shell. Type exit there by hand to continue with the script.

Now inside a bootstrap script there is no TTY attached, su www-data cannot start an interactive shell and exits immediately. The rest of the script is executed (obviously not as www-data user); and if there is exit somewhere, it will exit the script.

The cleanest way to deal with it is to insert whatever and something-else into a separate helper script, then you can invoke in your main script

su www-data -c "/path/to/the/helper/script"

The main script will wait for su to exit. When it happens, any following line is executed by the original user.

Another way is like this:

su www-data -c 'whatever; something-else'

or equivalently

su www-data -c '
whatever
something-else
'

The latter approach may be troublesome if the commands need quoting. There is no such problem with an additional script.

1
  • Another option could be a heredoc - su www-data <<EOF ... EOF
    – Attie
    Commented Sep 25, 2018 at 15:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .