I am creating a script which runs a series of command that would download a website to a machine and sets up everything.
So most of the commands require root access. For example adding a vhost in /etc/apache2/sites-available
, enabling it, restarting apache, etc...
So in order to do that, I need to run the script with sudo
.
sudo ./install-website.sh
The website is located on a server with a git repository which is setup with a password-less SSH access. But that only works for the user dan
since the keys are in my home folder and not in the root's home folder.
So when it reaches this part:
git clone [email protected]:git-repo $PATH_TO_INSTALLATION
Since I started the script with sudo
, the user that is trying to initiate the git command is root. So the host keeps asking for the host's user's password.
I have tried the following command:
sudo -u $SUDO_USER git clone [email protected]:git-repo $PATH_TO_INSTALLATION
But it was still asking for the host's user's password.
Is it possible to tell sudo
to use the $SUDO_USER
's home path?
Most of the stuff are variables, and have to be variables as I will run this on more than 1 machine.
Alternative 1 - Configuring sudo
Sudo is configure in the
sudoers
file which you should only edit through thevisudo
command.This configuration file can override certain environment variables with the option
env_reset
. How to proceed:Then find a line that states:
and add after it (e.g. example with the HOME environement):
This example is for every sudo configuration you may have. You can also specify it on a per user/group basis. See sudoers manual page.
Alternative 2 - configuring SSH
You can use the configuration file of SSH to specify users, key to use, etc. I have explain that at SuperUser.
Proposed solution (but you will have to correct the missing and assumed bits), edit the file
/root/.ssh/config
and set its permissionchmod 0600 /root/.ssh/config
:Then as root, you can do the next command and it will use the proper SSH identifications:
Since the script is running as root, it can
su
straight to the unpriviliged user. Roots don't need tosudo
,sudo
is for lusers ;-).Assuming the unprivileged user is
dan
, and $PATH_TO_INSTALLATION is set in the surrounding script:Note that
$PATH_TO_INSTALLATION
must be writable bydan
.When I generated my ssh key a long time ago with
ssh-keygen
, I didn't choose the default path~/.ssh/id_rsa
. Thanks to zwets' comment, I remmebered that. I changed my key, and put it in~/.ssh/id_rsa
.Now both of the commands work:
With
sudo
As suggested in zwets' answer