简体   繁体   中英

Executing npm install in user data

I am attempting to create a launch template in aws with the following in the user data

#!/bin/bash
home=/home/ec2-user
nodev='8.11.2'
nvmv='0.33.11'

#install node
su - ec2-user -c "curl 
https://raw.githubusercontent.com/creationix/nvm/v${nvmv}/install.sh | bash"
su - ec2-user -c "nvm install ${nodev}"
su - ec2-user -c "nvm use ${nodev}"

# install git
yum install git -y

#clone the code
cd /home/ec2-user
su - ec2-user -c "git clone https://github.com/xyz/xdf.git"
cd /home/ec2-user/xdf

#install dependencies
su - ec2-user -c "npm install"
echo "test" > test.txt

#install pm2
su - ec2-user -c "npm install pm2 -g"

#run the server
su - ec2-user -c "pm2 run index.js"

The script is being executed and the repo is cloned but the npm install command is running on the dir /home/ec2-user rather than on /home/ec2-user/xdf. The test.txt is created in the correct place ie inside /home/ec2-user/xdf. How do I get npm install to run on /home/ec2-user/xdf. I tried just running npm install instead of su - ec2-user -c "npm install" , but it still giving the same results.

First of all userdata is running with root user permissions so you don't need to have sudo or su there. In case you want ec2-user to be owner of that dir so simply execute chown ec2-user:ec2-user /path/to/dir

Next, when you run su - ec2-user -c ... it is executed in /home/ec2-user dir and cd /home/ec2-user/xdf is not working here. Simply remove all su from your script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM