How to parse an S3 JSON file into environment variables for Serverless.ts

What is the syntax to parse an S3 .json file into individual environment variables in the Serverless.ts configuration?

I’ve tried the following without success to get the environment variable MY_SECRET set to the value of MY_SECRET in the bucket’s JSON.

functions: {
    hello: {
      environment: {
        MY_SECRET: "${s3:my-config/services/test/support-portal-api.json}"
      },

…this deploys but sets MY_SECRET to the entire contents of the JSON file

functions: {
    hello: {
      environment: {
        MY_SECRET: JSON.parse("${s3:my-config/services/test/support-portal-api.json}").MY_SECRET
      },

…this fails to deploy with :

SyntaxError: Unexpected token $ in JSON at position 0
      at JSON.parse (<anonymous>)

What is the correct syntax? The documentation isn’t very clear. Please note this is a Typescript (Serverless.ts) file.

1 Like

@urb4nc4rl Hello from the future, I need to do this. Did you figure out how to do it?

Hi there!

I have solved this using require and ‘magic quotes’.

My project structure is:

My root folder:
| - config
|   |-- dev.json
|   |-- prd.json

I simply use require at the beginning of my serverless.ts file:

const env = require(`./config/${process.env.STAGE||'dev'}.json`);
console.log('env: ', env);

Then, I use it as a JSON object in the environment section:

    environment: {
      AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
      NODE_OPTIONS: '--enable-source-maps --stack-trace-limit=1000',
      CLIENT_ID: env.CLIENT_ID,
      MNG_CLIENT_ID: env.MNG_CLIENT_ID,
      PRIVATE_KEY: env.PRIVATE_KEY,
      HOST: env.HOST,
      ORIGIN: env.ORIGIN,
      RPID: env.RPID,
      INCODE_URL: env.INCODE_URL,
      INCODE_API_KEY: env.INCODE_API_KEY,
      INCODE_FLOW_ID: env.INCODE_FLOW_ID,
    },