Chef bash resource not executing as specified user

Solution 1:

The problem is (likely) not Chef running the command as the wrong user, but that the shell running your script is not a login shell. This means that some environment variables (like HOME) will not be set the way you expect, leading npm to try to write files in the wrong place.

The problem is discussed in issue CHEF-2288. While that remains outstanding, you could try adding HOME=/home/hubot-user in your code block, before npm is invoked.

Solution 2:

Taken from a comment in CHEF-2288:

environment ({ 'HOME' => ::Dir.home('USERNAME'), 'USER' => 'USERNAME' })

Worked for me!

In your case:

environment ({ 'HOME' => ::Dir.home(hubot_user), 'USER' => hubot_user })

Solution 3:

After: https://serverfault.com/a/432916/129232

To execute a script or a command as a user, you need to combine su -l and bash -i, e.g.:

 execute "npm_install" do
    command "su vagrant -l -c 'cd /shared-with-host/helperScripts/ && bash -i npm install -g q zombie should mocha coffee-script'" 
    action :run
  end

Because of some bugs, chef does not set properly the environment for the specified user in execute.