Search code examples
bashrbenv

How to execute rbenv as a different user?


I am writing an installation script in bash that will be run as root upon provisioning a new server. It will install rbenv for the deploy user and install some default rubies/gems. My script is complete to the point of setting up rbenv, but it cannot install rubies as the deploy user. I know that rbenv is set up correctly because when I SSH as the deploy user I have access to rbenv like usual. Here's what I have so far:

# install rbenv
git clone https://github.com/sstephenson/rbenv.git /home/deploy/.rbenv

# install ruby-build and auto-rehash plugins
git clone https://github.com/sstephenson/ruby-build.git /home/deploy/.rbenv/plugins/ruby-build
git clone https://github.com/sstephenson/rbenv-gem-rehash.git /home/deploy/.rbenv/plugins/rbenv-gem-rehash

# fix permissions since we've been running as root
chown -R deploy:deploy /home/deploy/.rbenv

# setup rbenv
echo "export PATH=\"~/.rbenv/shims:~/.rbenv/bin:$PATH\"" >> /home/deploy/.bashrc
echo 'eval "$(rbenv init -)"' >> /home/deploy/.bashrc

# now install default ruby
sudo -i -u deploy /bin/bash - <<-EOF
    rbenv install $ruby_version
    rbenv global $ruby_version
    echo 'gem: --no-ri --no-rdoc' > ~/.gemrc
    gem install bundler
EOF

I have tried every combination of -i, -H, -l that I can think of but I keep getting:

/bin/bash: rbenv: command not found

What am I doing wrong?


Solution

  • If rbenv is installed and you receive a command not found error, that means that you likely have a PATH problem. You put the necessary PATH into the deploy user's ~/.bashrc file. However, bash only guarantees to read ~/.bashrc when the shell is both interactive and non-login. I would suggest either putting the PATH statement in a script that is read or, possible easier, provide explicit paths in your here script.

    When invoked as a login shell (as per sudo -i), bash will read /etc/profile, if it exists. and then it will read the first file it finds (and only the first) from the list: ~/.bash_profile, ~/.bash_login, and ~/.profile.

    As a final note, the ~/.bashrc file that is created by the script is owned by root. You might want to make sure that your user has permission to read it or else give him ownership via chown as you do for his ~/.rbenv files.