3

For AWS EC2 (Amazon Linux) launch configuration, I have set some userdata having some sequence of commands which looks like below.

#!/bin/bash -exv \n", 
"#Execute Init resource\n", 
"whoami\n", 
"pwd\n", 
"npm -v\n",

Upon instance startup, user data is executing fine and native commands like "whoami" are giving correct output in cloud-init-output.log but it is giving error for npm command with error message like "npm command not found".

But, when I ssh to the instance and try executing some npm commands, it is working fine.

Could some one please guide me in solving this?

Thanks

2 Answers2

7

The user data is executed as root. It is possible the path to npm is not in root's PATH. Specify the full path to npm and it should work.

The reason it works when you ssh is because npm is available in your PATH.

helloV
  • 42,534
  • 4
  • 100
  • 125
  • This is the correct reason. I missed the part about ssh. Removed my answer. – Rumesh Eranga Hapuarachchi Jul 19 '17 at 17:42
  • Thank you @helloV . I will try this. Can you help me in understanding why PATH is not available to 'root' user at instance startup while it is available to the same user via ssh? – Jayavardhan Gange Jul 20 '17 at 05:42
  • Hi @helloV and all, just an update that, I updated my user data script with a statement to print PATH. i.e echo $PATH and when I look into cloud-init-output.log I could see this statements output as "/sbin:/usr/sbin:/bin:/usr/bin" and in ssh terminal when I do "echo $PATH" I could see as "/root/.nvm/versions/node/v6.11.1/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin" – Jayavardhan Gange Jul 20 '17 at 05:46
0

@helloV's answer works fine. Thanks to @helloV. Still, I tried to find more about PATH issues of root user during instance startup and I found out that nvm.sh of NVM (Node version manager) package in my AMI extends the PATH to add path for 'npm' and 'node'.

This nvm.sh is triggered from .bash_profile -> .bashrc

One thing was clear that .bash_profile of root user was not executed before user data script execution during instance startup. So I sourced .bash_profile in my user data script and now further npm commands in user data script are working fine.

Found out nvm.sh details in https://github.com/creationix/nvm/issues/381 Thanks to Ben Creasy.

Hope this helps.

  • "So I sourced .bash_profile in my user data script"..Does this mean adding "source ~/.bash_profile" in the userdata script.I am sorry, i am not well-versed in scripting so asking this question but I am facing error with regards to npm – anuragb26 Jul 02 '19 at 12:58