Reference Dynamic Values from Javascript
You can reference JavaScript modules to add dynamic data into your variables.
Exporting an object
To rely on exported someModule property in myFile.js you'd use the following code ${file(./myFile.js):someModule})
e.g.
// scheduleConfig.js
module.exports.rate = 'rate(10 minutes)'
# serverless.yml
service: new-service
provider: aws
functions:
hello:
handler: handler.hello
events:
- schedule: ${file(./scheduleConfig.js):rate} # Reference a specific module
Exporting a function
Note: the method described below works by default in Serverless v3 and later versions, but it requires the variablesResolutionMode: 20210326 option in v2.
A variable resolver function receives an object with the following properties:
options- An object referencing resolved CLI params as passed to the commandresolveVariable(variableString)- Async function which resolves provided variable string. String should be passed without wrapping (${and}) braces. Example valid values:file(./config.js):SOME_VALUEenv:SOME_ENV_VAR, null(end with, null, if missing value at the variable source should be resolved withnull, and not with a thrown error)
resolveConfigurationProperty([key1, key2, ...keyN])- Async function which resolves specific service configuration property. It returns a fully resolved value of configuration property. If circular reference is detected resolution will be rejected.
The resolver function can either be sync or async. Note that both resolveConfigurationProperty and resolveVariable functions are async: if these functions are called, the resolver function must be async.
Here is an example of a resolver function:
// config.js
module.exports = async ({ options, resolveVariable }) => {
// We can resolve other variables via `resolveVariable`
const stage = await resolveVariable('sls:stage');
const region = await resolveVariable('opt:region, self:provider.region, "us-east-1"');
...
// Resolver may return any JSON value (null, boolean, string, number, array or plain object)
return {
prop1: 'someValue',
prop2: 'someOther value'
}
}
It is possible to reference the resolver's returned value:
# serverless.yml
service: new-service
custom: ${file(./config.js)}
Or a single property (if the resolver returned an object):
# serverless.yml
service: new-service
custom:
foo: ${file(./config.js):prop1}