I'm deploying a nodejs app to a EC2 instance on AWS through codecommit/codebuild/codedeploy. In my appspec.yml file for codedeploy, I have a script called application_start.sh, which is called when the application starts. I use it to restart pm2.


pm2 delete /home/ubuntu/server/app.js 2> /dev/null
CREDENTIALS_SOURCE=$CREDENTIALS_SOURCE pm2 start /home/ubuntu/server/app.js --update-env

As you can see, I have an env variable ($CREDENTIALS_SOURCE) which I read in the bash script to set an env variable for my nodejs code.

The problem is: when the script runs the first time (automatically through the aws pipeline), the $CREDENTIALS_SOURCE variable isn't read and the server crashes. When I SSH into the server and I execute the exact same commands as like in the sh-script, it works.

When I change the bash script to CREDENTIALS_SOURCE=dev, so hardcoding "dev" instead of reading it out from the server env variable, it also works.

I have export CREDENTIALS_SOURCE=dev in .bashrc (and sourced it). When I do printenv I see the environment variable.

  • Where are you expecting to set the value of the variable when you run this through the aws pipeline?
    – Kusalananda
    Commented Jun 6, 2022 at 19:27
  • 1
    If you get this varible outside the script CREDENTIALS_SOURCE=$CREDENTIALS_SOURCE is 100% redundant and does absolutely nothing. Where do you define this variable? You could simply add something like . /script/which/defines/cred_source.sh or CREDENTIALS_SOURCE=$(cat /some/file) Commented Jun 6, 2022 at 19:29
  • Does shebang #!/bin/bash -l help ?
    – gerhard d.
    Commented Jun 6, 2022 at 19:30
  • the variable is set on the server, not in the aws process itself
    – Sam Leurs
    Commented Jun 6, 2022 at 19:31
  • 1
    How is it set? For whom? Where? If where it's set and this script run independently, your script cannot know about that. Again, CREDENTIALS_SOURCE=$CREDENTIALS_SOURCE is 100% nonsensical and cannot possibly work. You define a variable which is supposedly already defined e.g. via export. You can remove this statement and the script will continue to work in your SSH shell because $CREDENTIALS_SOURCE is set as a bash env variable. Commented Jun 6, 2022 at 19:32

1 Answer 1


I found a solution, it works but I don't know if this is the way to go.

Clearly, pm2 can't read env variables from the server. When I run node app.js instead of pm2 start app.js, the env variable is accessible for the nodeJS app.

With the following command, I got it working for pm2:

sudo -E pm2 start app.js

My guess is that the env variable is not stored in the ubuntu user, but in the root (sudo) user. Is this correct?

The above isn't a perfect solution. A better solution:

  1. add export CREDENTIALS_SOURCE=dev to /etc/profile
  2. add source /etc/profile in application_start.sh before starting pm2

This works!


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .