How to pass value from serverless yml file to js file?

Viewed 556
serverless.yml file    
provider:
      name: aws
      runtime: nodejs12.x
      memorySize: 512
      stage: ${opt:stage, 'test'}
      timeout: 30
    ##
    ##...
    custom:
      getValue: ${file(key.js):randomVal} //pass the string from here


key.js file
module.exports.randomVal = async (context) => {
    #code //get the string here
    console.log(context.providers);
};

In the above code, I am calling randomVal() function from the serverless yml file, I want to pass a string to that function from yml file. Is there any way to achieve it?

2 Answers

I reviewed the serverless docs, and there doesnt seem to be an official way to do this.

However, as a work around, you can just parse your serverless.yml file in your key.js file using an npm package like https://www.npmjs.com/package/yaml

Then do something like this:

custom:
  getValue:
    fn: ${file(key.js):randomVal}
    params: 
      someVar: foo
      someOtherVar: bar

When you parse serverless.yml in your key.js, you can then just use normal not notation to get the params:

const YAML = require('yaml')
const fs = require('fs')

const file = fs.readFileSync('./serverless.yml', 'utf8')
const parsedYaml = YAML.parse(file)

module.exports.randomVal = () => {
    let myVar = parsedYaml.custom.getValue.params.someVar
};

My recommendation is to use Serverless environment variables.

In your serverless.yml file you have a section environment under provider. Then those values will be populated for all your lambdas as process env varibles.

For example, having this section in you serverless.yml:

    
provider:
  name: aws
  environment:
    SOME_USEFUL_VALUE: 'some_val'

Then in your typescript files you can use this value as

const THE_USEFUL_VALUE = process.env.SOME_USEFUL_VALUE
Related