通过 Cloudformation 使用函数 URL 部署 AWS Lambda

Deploy AWS Lambda with function URL via Cloudformation

几天以来,AWS Lambdas can be exposed as web services directly without an API Gateway

这在通过 UI 控制台设置时工作正常,但我似乎无法使用 Cloudformation 完成它,因为 AuthType: NONE 没有附加资源策略。如果没有该策略,当我尝试通过函数 url.

访问 Lambda 时,我会从 AWS 获得 "message": "Forbidden"

我的 Lambda 如下:

exports.handler = async event => {
    return {
        statusCode: 200,
        body: JSON.stringify("Hello World")
    }
}

这是 CFN 模板:

AWSTemplateFormatVersion: "2010-09-09"

Parameters:
  stackName:
    Type: String
  lambdaFile:
    Type: String
  lambdaBucket:
    Type: String

Resources:
  lambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Action:
              - "sts:AssumeRole"
            Effect: "Allow"
            Principal:
              Service:
                - "lambda.amazonaws.com"
      Policies:
        - PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Action:
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
                Effect: "Allow"
                Resource:
                  - !Sub "arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${stackName}:*"
          PolicyName: "lambda"

  runtimeLambdaFunction:
    Type: "AWS::Lambda::Function"
    Properties:
      Code:
        S3Bucket: !Ref lambdaBucket
        S3Key: !Ref lambdaFile
      Environment:
        Variables:
          NODE_ENV: production
      FunctionName: !Sub "${stackName}-runtime"
      Handler: runtime.handler
      MemorySize: 128
      Role: !GetAtt lambdaRole.Arn
      Runtime: "nodejs14.x"
      Timeout: 5

  lambdaLogGroup:
    Type: "AWS::Logs::LogGroup"
    Properties:
      LogGroupName: !Sub "/aws/${stackName}"
      RetentionInDays: 30

  runtimeLambdaUrl:
    Type: "AWS::Lambda::Url"
    Properties:
      AuthType: NONE
      TargetFunctionArn: !Ref runtimeLambdaFunction

Outputs:
  runtimeLambdaUrl:
    Value: !GetAtt runtimeLambdaUrl.FunctionUrl

有趣的是,我可以通过 UI 控制台添加策略,然后它就起作用了。

这是 CFN 部署后 URL 功能的初始配置屏幕:

这是我按下“编辑”按钮时看到的:

点击“保存”后,我得到以下信息(注意蓝色框):

此外,当我再次进入“编辑”模式时,我现在看到以下内容:

之后,可以通过 URL.

访问该函数

我尝试将该策略添加到我的 CFN 堆栈中,作为 AWS::IAM::Policy 的独立策略,但它不是基于资源的策略或作为对 lambdaRole 的附加操作。但在任何一种情况下,我都无法添加 Principal 并且该策略没有效果。

有人知道我如何为具有函数 URL 的 Lambda 进行纯 Clouformation 部署吗?或者这是 Cloudformation and/or Lambda 中的错误?

您的模板丢失AWS::Lambda::Permission, thus its does not work. You already know what the permissions should be based on AWS console inspection, so you have to recreate those permissions using AWS::Lambda::Permission. This allows you to specify FunctionUrlAuthType