如何在Elastic Beanstalk上运行`npm update -g npm`?

Tim*_*mer 3 amazon-web-services node.js npm amazon-elastic-beanstalk

如何npm update -g npm在我们的Elastic Beanstalk实例启动时运行它们?对每个实例进行shell操作以手动运行update命令相当容易,但这不会通过扩展事件起作用,因为会自动添加更多实例.

如何通过自动缩放事件的方式在Elastic Beanstalk实例上获取最新版本的NPM?

Tim*_*mer 5

事实证明这个很棘手,需要进行一些挖掘和实验.

首先,快速了解Elastic Beanstalk的生命周期.在部署的每个实例上运行的AWS脚本采取了几个步骤.对于Node.JS服务器,有两个问题:

  • 安装Node.JS
  • npm install

安装Node.JS是我们可以介入并做一些魔术的地方.大多数错误促使人们想要对beanstalk实例进行魔法或其他事情,这些错误来自于该npm install步骤.

回到主题,AWS用于在beanstalk实例上安装节点的脚本是/opt/elasticbeanstalk/hooks/appdeploy/pre/40install_node.sh.它通常看起来像这样:

#!/bin/bash

set -xe

/opt/elasticbeanstalk/containerfiles/ebnode.py --action node-install
Run Code Online (Sandbox Code Playgroud)

此脚本安装了许多不同的节点版本/opt/elasticbeanstalk/node-install,包括在beanstalk配置中选择的版本.npm update -g npm使用位于该文件夹中的其中一个节点版本运行不是很好吗?

事实证明,beanstalk提供了一种在部署期间交换每个实例上的文件的机制.基本上,您.ebextensions在应用程序的文件夹中配置YAML文件.有两种方法可以在行中或在s3存储桶中引用文件内容.我使用s3 bucket方法,给出一个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
Run Code Online (Sandbox Code Playgroud)

注意S3Access财产.我们将存储桶保密,允许访问aws-elasticbeanstalk-ec2-role使用的IAM.

现在我们只需要40install_node.sh运行npm update 的版本:

#!/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
Run Code Online (Sandbox Code Playgroud)

您也可以将任何自定义节点安装在此文件中.请记住要密切关注节点的路径,它会随着beanstalk配置中节点版本的增加而改变.