AWS EC2 用户数据未 运行,未为 AMI 保存节点

AWS EC2 User Data Not Running, Node Not Saved for AMIs

我正在 运行为 Amazon Linux AMI 上的 AWS EC2 创建以下用户数据脚本。我想要 运行 一个简单的 socketio 服务器,但是每当我停止和启动实例时,脚本不会 运行。当我通过连接门户 SSH 和 运行 这些命令时,它起作用了。此外,当从我的正常运行的实例创建 AMI 时,Git 存在,但在从该 AMI 生成的实例上不存在节点。

我按照 AWS 文档安装节点,它暗示它应该与 AMI 一起工作。

#!/bin/bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install node
sudo yum install git -y
git clone https://github.com/justincervantes/socketio-server-demo.git
cd socketio-server-demo
npm i
node index.ts

提前感谢您的建议。

用户数据 shell 脚本必须以 #! 字符和您要读取脚本的解释器的路径(通常为 /bin/bash)开头。

因此,对于此脚本,请在开头添加以下内容:

#!/bin/bash

您还需要获取 NVM 文件以确保变量在当前 shell

中可用

你的脚本将像下面这样工作:

#!/bin/bash
apt-get -y update
cat > /tmp/subscript.sh << EOF
# START UBUNTU USERSPACE
echo "Setting up NodeJS Environment"
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
echo 'export NVM_DIR="/home/ubuntu/.nvm"' >> /home/ubuntu/.bashrc
echo '[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm' >> /home/ubuntu/.bashrc
# Dot source the files to ensure that variables are available within the current shell
. /home/ubuntu/.nvm/nvm.sh
. /home/ubuntu/.profile
. /home/ubuntu/.bashrc
# Install NVM, NPM, Node.JS & Grunt
nvm install node
sudo yum install git -y
git clone https://github.com/justincervantes/socketio-server-demo.git
cd socketio-server-demo
node index.ts
EOF

chown ubuntu:ubuntu /tmp/subscript.sh && chmod a+x /tmp/subscript.sh
sleep 1; su - ubuntu -c "/tmp/subscript.sh"