Install nvm as different user

Hello, I’m trying to install specific versions of nvm, nodejs with npm for a setup which is quite manual at present.
we have a shell script that works when run locally, but it doesn’t work when run using packer.

usually there are either permission issues, or it says nvm command not found.

are there any suggestions?

the shell script that does it normally is this

sudo -H -u nodejs $(which bash) -c 'curl -o- | bash'
sudo -H -u nodejs $(which bash) -c 'nvm install 8.16.0'
sudo -H -u nodejs $(which bash) -c 'nvm use 8.16.0 ; nvm alias default 8.16.0 ; npm i npm@latest' ## THIS MAY FAIL, IT NEEDS TO BE TESTED
sudo -H -u nodejs $(which bash) -c 'npm i -g pm2@2.10.4'

# As nodejs user - in /home/nodejs
# create *ecosystem.config.js* with the following
touch /home/nodejs/ecosystem.config.js
cat <<EOF >> /home/nodejs/ecosystem.config.js
module.exports = {
   * Application configuration section
  apps : [

    // First application
      name      : 'unified-api',
      script    : '/usr/src/app/latest/cluster.js',
      watch     : ['/usr/src/app/reload/unified-api'],
      cwd       : '/usr/src/app/latest/',
      env: {
        COMMON_VARIABLE: 'true',
        NODE_ENV: 'production'
      "sudo -H -u nodejs $(which bash) -c 'sudo /home/nodejs/.nvm/'",

I’ve tried a number of ansible playbook roles from ansible galaxy however they still seem to have issues.

how can I run commands as a different user, and change all the environment variables so that they refer to the bashrc in the nodejs user before the script is run?


What builder are you using?

Several of Packer’s builders support an ssh_username parameter which specifies the account name to be used when logging into the instance via SSH. All provisioning commands would be executed as this user unless otherwise specified.

An alternate method would be to upload the script using the file provisioner, and run a shell provisioner which executes the script using the runuser command. For example:

chmod +x
runuser --login nodejs --command './'

This should avoid any permissions or PATH issues encountered when the script is run.

Hi Blake, thank you for this,
What builder? assuming you mean the type, its the amazon-ebs builder.

I’m going to give your suggestion a try and see what the outcome is


Thanks Blake, using sudo runuser command works! that’s resolved something that’s taken a lot of time, so thank you.

FYI for anyone else running across this, you need to make sure util-linux is installed, which contains the runuser command.


1 Like