首页 > 解决方案 > 如何在“serverless.yml”中引用 lambda 版本?

问题描述

我正在使用serverless将 lambda 部署到 AWS。我有一个案例,它lambda在部分中定义,functions但配置并发配置是resources因为我需要使用Condition. 我遇到的问题是我如何引用已发布的 lambda 版本resources

functions:
  getTransactionsHandler:
    ...

resources:
  Conditions:
    CommonPCNotZero: !Not [!Equals [0, '${self:custom.commonPC}']]
  Resources:
    !If 
      - CommonPCNotZero
      - getTransactionsHandler:
        Type: AWS::Lambda::Alias
          Properties:
            FunctionName: !Ref GetTransactionsHandlerLambdaFunction
            FunctionVersion: HOW CAN I GET THE VERSION?
            ProvisionedConcurrencyConfig:
              ProvisionedConcurrentExecutions: '${self:custom.commonPC}'
      - !Ref AWS::NoValue

标签: amazon-web-servicesaws-lambdaserverless-framework

解决方案


在 serverless.yml 文件中放置一个占位符作为参考。

[无服务器脚本插件] LambdaFunctionARN:THIS_IS_SET_IN_SCRIPT

可编写脚本的插件使用钩子

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

脚本 completeLambdaAssociation.js 通过搜索 AWS::Lambda::Version 资源来更新 LambdaFunctionARN。

// 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`);

推荐阅读