Search code examples
node.jsamazon-web-servicesamazon-elastic-beanstalkaws-codepipeline

Passing Variables from CodeBuild or CodePipeline to use in Node Web App


I'm having an issue where I'm trying to pass in a simple string variable to be referenced in a node web app running on Elastic Beanstalk. It's used for a basic conditional within the app, but when I console.log(process.env) the variable does not show. I've tried listing it in CodePipeline settings, CodeBuild settings, and the buildspec.yml file with no success.

The documentation is either vague, incorrect, or overly complicated for what I'm trying to achieve. I literally just need to pass in something like VARIABLE_NAME="someName" to be used inside the node app when it's deployed/live on Elastic Beanstalk.

Any help would be greatly appreciated!!!


Solution

  • Not sure if you are using a CodeDeploy step after the CodeBuild, but you can add environment variables in your buildspec.yml like this:

    version: 0.2
        
    env:
      variables:
        MY_VARIABLE: "my_value"
        
    phases:
      ...
    

    Or you can add them in the CodeBuild's step environment variables in the CodePipeline console:

    CodeBuild environment variables

    Those variables can be accessed in the CodeBuild's buildspec.yml or CodeDeploy's appspec.yml with $MY_VARIABLE. So if you have a deployment script that runs from your appspec.yml you could do something like:

    # Access environment variable
    MY_VARIABLE=$MY_VARIABLE  
    
    # Export the variable to your app's environment
    export MY_VARIABLE
    

    For it to be available to your app, you should either export the variable so it is available in your app's environment like the export command seen above (remember to restart/reload the service if you do this so that the app will be able to access the new env variable) or add it to a local file (like an .env) that you can read from your app.

    # Create .env file
    ENV_FILE=".env"
    touch $ENV_FILE  
    
    # Export the variable to the .env file
    echo "MY_VARIABLE=$MY_VARIABLE" >> $ENV_FILE
    

    I do this regularly to deploy my backend using environment variables. In my case I create a .env file that is added to a docker image, and the backend reads that .env file to retrieve different settings.

    I hope this helps you solve the issue.