Ben
Ben

Reputation: 6086

Setting EC2 Environment Variables with CodeDeploy, Parameter Store and PM2

I am deploying a Node.js app to EC2 using CodeDeploy. I am storing credentials within AWS Systems Manager, Parameter Store however cannot find a method to expose these to my application.

I am using PM2 for process management. I can successfully retrieve the parameter from the Parameter Store on the target machine, so there are no permission issues. For example:

aws ssm get-parameters --region us-east-1 --names LOCAL_CACHE_PATH --with-decryption --query Parameters[0].Value`

...successfully returns the correct string. I attempt to use this in my applicationStart.sh CodeDeploy file and start the app:

#!/bin/bash
export LOCAL_CACHE_PATH=$(aws ssm get-parameters --region us-east-1 --names LOCAL_CACHE_PATH --with-decryption --query Parameters[0].Value)

pm2 start ecosystem.config.js --env production

LOCAL_CACHE_PATH returns undefined in my app when accessing process.env.LOCAL_CACHE_PATH.

So the environment variable is available within the applicationStart.sh script and yet undefined when the app starts from that script.

I am looking for a recommended approach to use environment variables from the Parameter Store with CodeDeploy.

I have read literally dozens of posts on similar topics but cannot resolve it. Very much appreciate any guidance.

Upvotes: 1

Views: 2016

Answers (1)

Ben
Ben

Reputation: 6086

The solution I am using is to write the environment variables to a .env file and use that in my app:

afterInstall.sh:

echo LOCAL_CACHE_PATH=$(aws ssm get-parameters --output text --region us-east-1 --names LOCAL_CACHE_PATH --with-decryption --query Parameters[0].Value) >> /home/ubuntu/foo/.env

Upvotes: 1

Related Questions