Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS EC2 Launch configuration user data - command not found

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

like image 240
Jayavardhan Gange Avatar asked Dec 13 '25 05:12

Jayavardhan Gange


2 Answers

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.

like image 141
helloV Avatar answered Dec 15 '25 03:12

helloV


@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.

like image 35
Jayavardhan Gange Avatar answered Dec 15 '25 02:12

Jayavardhan Gange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!