【问题标题】:How can I reference lambda version in `serverless.yml`?如何在“serverless.yml”中引用 lambda 版本?
【发布时间】:2021-05-12 09:59:16
【问题描述】:

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

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-services aws-lambda serverless-framework


    【解决方案1】:

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

    【讨论】:

    • 是否已经有来自无服务器的内置变体,还是我们还需要实现这个逻辑?
    猜你喜欢
    • 2018-11-11
    • 2020-09-11
    • 2023-03-17
    • 2020-01-11
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多