如何在我的 Elastic Beanstalk 实例启动时运行 npm update -g npm
?很容易进入每个实例以手动运行更新命令,但这不会通过扩展事件起作用,因为会自动添加更多实例。
如何通过自动缩放事件在 Elastic Beanstalk 实例上获取最新版本的 NPM?
最佳答案
事实证明这个很棘手,需要进行一些挖掘和实验。
首先,简要介绍一下 Elastic Beanstalk 的生命周期。在部署时在每个实例上运行的 AWS 脚本执行了几个步骤。对于 Node.JS 服务器,有两个有趣的地方:
- 安装 Node.JS
- 运行
npm install
安装 Node.JS 是我们可以介入并施展魔法的地方。大多数促使希望对 beantalk 实例施展魔法、或其他事情的错误都来自 npm install
步骤。
回到主题,AWS 用于在 beantalk 实例上安装 Node 的脚本是 /opt/elasticbeanstalk/hooks/appdeploy/pre/40install_node.sh
。它通常看起来像这样:
#!/bin/bash
set -xe
/opt/elasticbeanstalk/containerfiles/ebnode.py --action node-install
此脚本将一堆不同的 Node 版本安装到 /opt/elasticbeanstalk/node-install
,包括在 beantalk 配置中选择的版本。使用位于该文件夹中的 Node 版本之一运行 npm update -g npm
不是很好吗?
事实证明,beanstalk 提供了一种机制,可以在部署期间交换每个实例上的文件。基本上,您在应用程序的 .ebextensions
文件夹中配置 YAML 文件。有两种方法可以引用文件内容,在线或在 s3 存储桶中。我使用 s3 存储桶方法,给出一个如下所示的 node.config
YAML:
files:
"/opt/elasticbeanstalk/hooks/appdeploy/pre/40install_node.sh" :
mode: "000775"
owner: root
group: users
source: https://s3.amazonaws.com/bucketname/40install_node.sh
authentication: S3Access
Resources:
AWSEBAutoScalingGroup:
Metadata:
AWS::CloudFormation::Authentication:
S3Access:
type: S3
roleName: aws-elasticbeanstalk-ec2-role
buckets: bucketname
注意 S3Access
属性。我们将存储桶保密,使用 IAM 授予对 aws-elasticbeanstalk-ec2-role
的访问权限。
现在我们只需要一个运行 npm 更新的 40install_node.sh
版本:
#!/bin/bash
set -xe
/opt/elasticbeanstalk/containerfiles/ebnode.py --action node-install
# Update npm
cd /opt/elasticbeanstalk/node-install/node-v0.12.2-linux-x64/bin/ && /opt/elasticbeanstalk/node-install/node-v0.12.2-linux-x64/bin/npm update npm -g
您也可以将您的 Node 安装的任何定制放在这个文件中。请记住注意 Node 的路径,它会随着 beantalk 配置中 Node 版本的增加而改变。
关于node.js - 如何在 Elastic Beanstalk 上运行 `npm update -g npm`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31260116/