Skip to content

Instantly share code, notes, and snippets.

@jeffsheets
Last active May 25, 2023 05:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffsheets/6865045c8c10d3de074469ae51c0af0b to your computer and use it in GitHub Desktop.
Save jeffsheets/6865045c8c10d3de074469ae51c0af0b to your computer and use it in GitHub Desktop.
JS to read AWS SSM variables for use in Gitlab CI process
#This is used locally by Create-React-App during development
#Cognito Region
REACT_APP_REGION=us-east-1
REACT_APP_USER_POOL_ID=us-east-1_youruserpoolid
REACT_APP_APP_CLIENT_ID=yourcognitoappclientidgoeshere
# Ignore our Gitlab CI generated SSM file
.env.ssm
#Reusable script definition
.build-script:
script: &build_script
- yarn install --frozen-lockfile
- echo "Loading AWS SSM Variables into .env.ssm file"
- export AWS_PROFILE=${CI_ENVIRONMENT_NAME}
- echo AWS_PROFILE is ${AWS_PROFILE}
- node ./read-ssm.js
- echo "Building files..."
- env $(cat .env.ssm | xargs) yarn build
- echo "Build successful!"
artifacts: &build_artifacts
name: "$CI_JOB_NAME-$CI_COMMIT_REF_NAME"
paths:
- build/
#Build for development on every push
build-dev:
stage: build
only:
- branches
except:
- master
- develop
environment:
name: development
script: *build_script
artifacts: *build_artifacts
/**
* process.env items are configured in .env files or environment variables
* and can be overriden at build time
* see https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
*/
/** AWS config */
export const REGION = process.env.REACT_APP_REGION;
export const USER_POOL_ID = process.env.REACT_APP_USER_POOL_ID;
export const APP_CLIENT_ID = process.env.REACT_APP_APP_CLIENT_ID;
const fs = require('fs');
const AWS = require('aws-sdk');
/**
* Used by the build process to inject AWS SSM params into environment variables
*
* NOTE: To run this locally you may need to either set AWS_REGION env var
* or use the value in your ~/.aws/config file by:
* AWS_SDK_LOAD_CONFIG=true node ./read-ssm.js
*/
/**
* All of these keys will be looked up in SSM and their values added to the build environment
*/
const SSM_NAMES = {
'/cognito/sample/pool/id': 'REACT_APP_USER_POOL_ID',
'/cognito/sample/client/web/id': 'REACT_APP_APP_CLIENT_ID'
};
const writeEnvFile = keyVals => {
fs.writeFileSync('./.env.ssm', keyVals.join('\n'));
};
const retrieveParams = async () => {
const ssm = new AWS.SSM();
const params = await ssm
.getParameters({
Names: Object.keys(SSM_NAMES)
})
.promise();
const keyVals = params.Parameters.map(p => `${SSM_NAMES[p.Name]}=${p.Value}`);
//Grab the region from the AWS_REGION or AWS_SDK_LOAD_CONFIG setting
keyVals.push(`REACT_APP_REGION=${AWS.config.region}`);
console.log(keyVals);
writeEnvFile(keyVals);
};
retrieveParams();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment