Search code examples
javascriptyamlaws-cloudformationserverless-framework

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


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?


Solution

  • 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
    };