Cloudformation 依赖性问题 - AWS::Serverless::Function 中的 AutoPublishAlias

Cloudformation Dependency Issue - AutoPublishAlias in AWS::Serverless::Function

我正在使用 SAM 模板部署 Lambda 函数和 api 网关。我正在使用 AWS::Serverless::Function 来定义我的 lambda 函数。我正在使用 AWS::Serverless::Api 来定义我的 API。我还使用 AWS::Lambda::Permission 向 api 网关授予该功能的权限。

问题是 AWS::Lambda::Permission 的资源创建失败,因为我的别名不可用。我的 LambdaFunction 资源创建了别名,但在创建之前,Lambda 权限资源创建被触发,如果它没有看到提到的别名,它就会失败。

我使用"aws cloudformation deploy"部署模板

将 DependsOn 属性添加到 LambdaPermission 资源不起作用

> LambdaFunction:
>     Type: AWS::Serverless::Function
>     Properties:
>       Handler: MyHandler
>       Runtime: !Ref LambdaJavaVersion
>       CodeUri: ./build.jar
>       Description: !Sub "${LambdaName} function"
>       Role: !GetAtt LambdaIAMRole.Arn
>       FunctionName: !Ref LambdaName
>       AutoPublishAlias: prod
> APIResource:
>   DependsOn: LambdaFunction
>   Type: AWS::Serverless::Api
>   Properties:
>     DefinitionUri: ./swagger/swagger.yml
>     EndpointConfiguration: REGIONAL
>     StageName: prod
> 
> LambdaPermission:
>   DependsOn: 
>     - LambdaFunction
>     - APIResource
>   Type: AWS::Lambda::Permission
>   Properties:
>     FunctionName: !Join
>       - ""
>       - [!GetAtt LambdaFunction.Arn,":","prod"]
>     Action: lambda:InvokeFunction
>     Principal: apigateway.amazonaws.com
>     SourceArn: !Join
>         - ""
>         - [!Sub "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}",':',!Ref
> APIResource,'/*/*/*']

我想仅在 Alias 发布后创建 LambdaPermission。

在我自己努力解决之后,我在 documentation:

中找到了这个

AutoPublishAlias Property Is Specified

When the AutoPublishAlias property of an AWS::Serverless::Function is specified, AWS SAM generates the following AWS CloudFormation resources:

AWS::Lambda::Alias and AWS::Lambda::Version.

AWS::Lambda::Alias

LogicalId: <function‑LogicalId>Alias<alias‑name>

<alias‑name> is the string that AutoPublishAlias is set to. For example, if you set AutoPublishAlias to live, the LogicalId is: MyFunctionAliaslive.

Referenceable property: <function‑LogicalId>.Alias

最后一行是解决方案。因此,要使您的权限取决于别名,并因此仅在创建别名后才创建,您可以通过这种方式引用别名:

YAML

LambdaPermission:
  Type: AWS::Lambda::Permission
  Properties:
    FunctionName: !Ref LambdaFunction.Alias
    Action: lambda:InvokeFunction
    Principal: apigateway.amazonaws.com

JSON

"LambdaPermission": {
  "Type": "AWS::Lambda::Permission",
  "Properties": {
    "FunctionName": {
      "Ref": "LambdaFunction.Alias"
    },
    "Action": "lambda:InvokeFunction",
    "Principal": "apigateway.amazonaws.com"
  }
}

DependsOn 属性 不是必需的,因为权限现在隐式取决于要创建的别名。