Referencing Lambda version in other variables

This can be achieved with the [serverless-scriptable-plugin](https://github.com/weixu365/serverless-scriptable-plugin). As an example, I put a placeholder for the reference in my serverless.yml file

LambdaFunctionARN: THIS_IS_SET_IN_SCRIPT

The scriptable plugin uses a hook

custom:
     scriptHooks:
           before:aws:package:finalize:saveServiceState: scripts/completeLambdaAssociation.js

The script completeLambdaAssociation.js updates the LambdaFunctionARN by searching for the AWS::Lambda::Version resource.

// serverless injected by serverless-scriptable-plugin
// noinspection JSUnresolvedVariable
const sls = serverless;

// noinspection JSUnresolvedVariable
const resources = sls.service.provider.compiledCloudFormationTemplate.Resources;
const resourceType = 'AWS::Lambda::Version';
const prefix = 'RewriteUriLambdaVersion';
const resourceNames = Object.keys(resources)
    .filter(name => resources[name].Type === resourceType && name.startsWith(prefix))
if (resourceNames.length !== 1) {
    throw Error(`Must have exactly 1 resource of type ${resourceType} and prefix ${prefix}, found ${resourceNames}`);
}
const distConfig = resources['CFDistribution']['Properties']['DistributionConfig'];
distConfig['DefaultCacheBehavior']['LambdaFunctionAssociations'][0]['LambdaFunctionARN'] = {Ref: resourceNames[0]};
console.log(`[${__filename}] Updated LambdaFunctionARN on first LambdaFunctionAssociation on DefaultCacheBehavior`);
1 Like