Access cli options when referencing variables in javascript files

Is there a way to to access the cli options when referencing variables in javascript files? I’d like to do something like:

// myCustomFile.js
module.exports.hello = (options) => {
   // Code that generates dynamic data
   return `hello ${options.stage}`;

# serverless.yml
service: new-service
provider: aws
      handler: handler.hello
         someVar: ${file(../myCustomFile.js):hello}

Yep, but it’s a bit of a daisy-chain…

In the environment section (of your provider or specific function) you can set a variable that is:

  OPT_STAGE: ${opt:stage}

And then referencing that In your function code:

const stage = process.env.OPT_STAGE;

I’d recommend setting a default, in case you forget to provide an option at deploy time.

I also think the reference has to be opt (not options as in your example), but I haven’t tested it (and the docs only show opt).

1 Like

Thanks. Does the job perfectly

Just in case it helps someone else I came up with an alternative solution yesterday. Less daisy chaining but also less flexible and a touch more code. I’ll probably switch to the above method

function getBuckets(stage) {
    return {
        bucketname: `some-bucket-name-${stage}`

module.exports = new Proxy({}, {
    get: (target, key) => () => getBuckets(key)

Then in the config, something like:

    - Effect: Allow
        - s3:ListMultipartUploadParts
      Resource: "arn:aws:s3:::${file(./lambdas/buckets.js):${opt:stage}.bucketname}"