Customize AWS ElasticBeanstalk NodeJS Install (use yarn)

Jiew Meng picture Jiew Meng · Jan 15, 2017 · Viewed 11k times · Source

Isit possible to configure EBS to install my NodeJS application using yarn package manager instead of NPM?

Answer

GreenRaccoon23 picture GreenRaccoon23 · Feb 7, 2017

I've figured out a way, but it is a little hacky.

  1. Create a .ebextensions/yarn.config file. (The name does not have to be 'yarn'.)
  2. Put this content into the file:

    files:
    # Runs right before `npm install` in '.../50npm.sh'
    "/opt/elasticbeanstalk/hooks/appdeploy/pre/49yarn.sh" :
        mode: "000775"
        owner: root
        group: users
        content: |
            #!/bin/bash
    
            app="$(/opt/elasticbeanstalk/bin/get-config container -k app_staging_dir)";
    
            # install node
            curl --silent --location https://rpm.nodesource.com/setup_8.x | bash -;
    
            # install yarn
            curl --silent --location https://dl.yarnpkg.com/rpm/yarn.repo | tee /etc/yum.repos.d/yarn.repo;
            yum -y install yarn;
    
            # install node_modules with yarn
            cd "${app}";
            yarn --production;
    

This ebextension creates a file which does 3 things:

  1. Installs node.
  2. Installs yarn.
  3. Installs node_modules with yarn.

In order to make Elastic Beanstalk run yarn install before it runs npm install, the file is created under /opt/elasticbeanstalk/hooks/appdeploy/pre. This turns the file into a pre-deployment hook, which means that Elastic Beanstalk will run it during the first phase of deployment. By default, there is another file in this directory called 50npm.sh, which runs npm install. Since Elastic Beanstalk runs the files in this directory alphabetically, 49yarn.sh (our file) will run before 50npm.sh (the default file), resulting in yarn install running before npm install.

One potential problem is that the environment variables set in the Elastic Beanstalk UI (under Configuration > Software Configuration) are not available at this point of the deployment phase. This is a big problem if you have an npm auth token there which you use to install private npm modules.

Another potential problem is that this installs node manually, so the "Node version" you specify in the Elastic Beanstalk UI (under Configuration > Software Configuration) will have no effect on the version of node your application uses; you need to specify it in this ebextension. Elastic Beanstalk's 50npm.sh both installs node and runs npm install. Since we have to run yarn install before that file runs, we also have to install node manually. Then, when Elastic Beanstalk goes to install node, it detects that node is already installed but does not verify that it is the correct version, so it skips the node installation.

For reference, the yarn installation instructions came from here: https://yarnpkg.com/docs/install#linux-tab