How can I run npm update -g npm
on my Elastic Beanstalk instances as they spin up? It's fairly easy to shell into each instance to run the update command manually, but this won't work through a scaling event, as more instances are added automatically.
How can i get the latest version of NPM on Elastic Beanstalk instances, in a way that works through an auto-scaling event?
If you don't want to add a script on to S3, you can simply put the following in your
.ebextensions
, assuming you're running node v12, for other versions the pathnode-v0.12.6-linux-x64
will be different.This should not be necessary. You can specify in your configuration what version of Nodejs you want to be running, and thus would be paired with the appropriate npm version. If you did want to have an older version of nodejs with a newer version of npm, then this exercise would be warranted.
In this case I would probably step on the npm install script in a file dropped into the .ebextensions folder (e.g. 00_default.config):
Replace CURRENTNODEVERSIONHERE with the correct path/version for your setup.
These are the available versions I see on my instances. You'll want to check your own resources to see what you're working with.
Location: /opt/elasticbeanstalk/node-install
It turns out this one is tricky, took a bit of digging and experimentation.
First, a quick bit about Elastic Beanstalk's lifecycle. There are several steps taken by AWS scripts running on each instance on deploy. For a Node.JS server, there are two of interest:
npm install
Installing Node.JS is where we can step in and do some magic. Most errors prompting the desire to do magic, or other things, to a beanstalk instance come from the
npm install
step.Getting back on topic, the script AWS used to install node on beanstalk instances is
/opt/elasticbeanstalk/hooks/appdeploy/pre/40install_node.sh
. It usually looks like this:This script installs a bunch of different node versions to
/opt/elasticbeanstalk/node-install
, including the one selected in the beanstalk configuration. Wouldn't it be nice to runnpm update -g npm
with one of the node versions sitting in that folder?It turns out beanstalk supplies a mechanism to swap out files on each instance during deploy. Basically you configure YAML files in a
.ebextensions
folder in your app. There are two ways to reference the file contents, in line, or in an s3 bucket. I use the s3 bucket approach, giving anode.config
YAML looking like this:Note the
S3Access
property. We keep the bucket private, granting access to theaws-elasticbeanstalk-ec2-role
using IAM.Now all we need is a version of
40install_node.sh
running the npm update:You can put any customization of your node install in this file as well. Just remember to keep an eye on the path to node, it will change as node versions go up in the beanstalk configuration.