`execute` as vagrant user, not root, with chef-solo?

Solution 1:

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

 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. The narced133's solution will not work.

Solution 2:

You can use environment to set the HOME and USER environment variables in your execute block.

execute "install q and zombiejs" do                                             
    cwd "/home/vagrant"                                                           
    user "vagrant"                                                                
    action :run   
    environment ({'HOME' => '/home/vagrant', 'USER' => 'vagrant'})                                                             
    command "npm install -g q zombie should mocha coffee-script"                  
end

I use this frequently to install vagrant plugins as the vagrant user inside my VMs. You could also set other environment variables if needed by whatever command you are trying to execute.

Solution 3:

It sounds like Chef is executing as the vagrant user but not searching the same PATH as your shell. Login using vagrant ssh and run which npm. It will return something like /path/to/bin/npm. Replace /path/to/bin/ below to force Chef to search the appropriate directory.

execute "install q and zombiejs" do                                             
    cwd "/home/vagrant"                                                           
    user "vagrant"                                                                
    action :run   
    path ["/path/to/bin/"]                                                               
    command "npm install -g q zombie should mocha coffee-script"                  
end