如何使用 .yaml 文件向 AWS Lambda 函数添​​加策略?

Posted

技术标签:

【中文标题】如何使用 .yaml 文件向 AWS Lambda 函数添​​加策略?【英文标题】:How to add Policies to AWS Lambda function using the .yaml file? 【发布时间】:2021-09-25 07:13:41 【问题描述】:

我正在使用AWS LambdaAPI GatewayRDS (mysql) 开发一个 REST API。我正在使用aws-sam 工具来构建、配置我的工作并将其发布到云端。

请检查下面我正在使用的template.yaml 文件。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  aaaa-restapi

  Sample SAM Template for aaaa-restapi

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 100

Resources:
  GetAllAccountTypesLambda:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aaaa-restapi
      Handler: com.aaaa.dao.accountingtype.GetAllAccountTypesLambda::getAllAccountTypes
      Runtime: java11
      MemorySize: 1024
      Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
        Variables:
          PARAM1: VALUE
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /accounttype
            Method: get

但是,要启用我的 lambda 函数来查找数据库,我必须从 AWS Web 控制台启用一些策略。我点击了这个链接 - https://ao.ms/the-provided-execution-role-does-not-have-permissions-to-call-createnetworkinterface-on-ec2/

以下是我在 AWS Web 控制台中为我的 Lambda 函数创建的策略。


  "Version": "2012-10-17",
  "Statement": [
    
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeNetworkInterfaces",
        "ec2:CreateNetworkInterface",
        "ec2:DeleteNetworkInterface",
        "ec2:DescribeInstances",
        "ec2:AttachNetworkInterface"
      ],
      "Resource": "*"
    
  ]

但是,从功能到功能,我无法在 Web 控制台中执行此操作。我需要在yaml 文件中完成这项工作。

使用上面提供的yaml 文件,我如何将这些权限赋予我的 Lambda 函数?

------------更新---------------

根据 Gaurauv 的评论,我对 yaml 文件进行了以下更改。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  aaaa-restapi

  Sample SAM Template for aaaa-restapi

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 100

Resources:
  GetAllAccountTypesLambda:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aaaa-restapi
      Handler: com.aaaa.dao.accountingtype.GetAllAccountTypesLambda::getAllAccountTypes
      Runtime: java11
      MemorySize: 1024
      Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
        Variables:
          PARAM1: VALUE
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /accounttype
            Method: get
      Role: !GetAtt LambdaRole.Arn
  
  LambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      Path: "/"
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      Policies:
        - PolicyName: 'ec2-access-policy'
          PolicyDocument:
            Statement:
              - Effect: Allow
                Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:CreateNetworkInterface
                  - ec2:DeleteNetworkInterface
                  - ec2:DescribeInstances
                  - ec2:AttachNetworkInterface
                Resource: '*'

但是部署失败,出现以下错误。

CREATE_FAILED                           AWS::IAM::Role                          LambdaRole                              Property AssumeRolePolicyDocument
                                                                                                                        cannot be empty.

【问题讨论】:

【参考方案1】:

根据IAM::Role 资源,创建角色时需要一个 AssumeRolePolicyDocument。此属性管理与此角色关联的信任策略。信任策略定义了哪些实体可以担任该角色。您只能将一个信任策略与一个角色相关联。

请为您的用例查找更新的角色资源

AWSTemplateFormatVersion: "2010-09-09"
Resources:
  LambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:CreateNetworkInterface
                  - ec2:DeleteNetworkInterface
                  - ec2:DescribeInstances
                  - ec2:AttachNetworkInterface
                Resource: '*'  

【讨论】:

感谢您的评论。我试图添加你的代码,但它失败了。我收到以下错误 - Failed to create changeset for the stack: aaaa-restapi, An error occurred (ValidationError) when calling the CreateChangeSet operation: Stack:arn:aws:cloudformation:us-east-1:716460586643:stack/aaaa-restapi/c20fc7e0-e648-11eb-a694-0e5b1dad9edf is in ROLLBACK_COMPLETE state and can not be updated. 对不起,上述问题是手动删除堆栈后排序的。现在它再次无法部署。错误是Encountered unsupported property ManagedPolicyArns 这是一个缩进问题,很抱歉我没有正确 lint。缩进已修复。 感谢您的回答。请问可以再请教吗?我在以安全方式使用 Lambda 访问 RDS 时遇到问题,所以我正在关注这个答案 - ***.com/a/68407716/1379286。问题是,我无法手动调整所有 lambda 函数的 VPS,我的 REST API 中有数百个。你能告诉我怎么做吗,我会发布另一个问题让你知道吗?即使对于上述答案之外的建议,我也持开放态度。 实现此目的的最快方法是通过 CloudFormation 为您的 Lambda 函数配置相同的 VPC。 Lambda 自动继承 Lambda 实例的 NACL 和安全组规则【参考方案2】:

您可以使用内联策略将角色附加到 lambda 函数。像这样的

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  aaaa-restapi

  Sample SAM Template for aaaa-restapi

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 100

Resources:
  GetAllAccountTypesLambda:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aaaa-restapi
      Handler: com.aaaa.dao.accountingtype.GetAllAccountTypesLambda::getAllAccountTypes
      Runtime: java11
      MemorySize: 1024
      Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
        Variables:
          PARAM1: VALUE
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /accounttype
            Method: get
      Role: !GetAtt LambdaRole.Arn



  LambdaRole:
    Type: "AWS::IAM::Role"
    Properties:
      Path: "/"
      ManagedPolicyArns:
        - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
      Policies:
        - PolicyName: 's3-access-policy'
          PolicyDocument:
            Statement:
              - Effect: Allow
                Action:
                  - s3:GetBucketLocation
                  - s3:GetBucketCORS
                  - s3:GetObjectVersionForReplication
                  - s3:GetObject
                  - s3:GetBucketTagging
                  - s3:GetObjectVersion
                  - s3:GetObjectTagging
                  - s3:ListMultipartUploadParts
                  - s3:ListBucket
                  - s3:ListBucketMultipartUploads
                  - s3:PutObject
                  - s3:PutObjectTagging
                  - s3:DeleteObject
                Resource: '*'

【讨论】:

感谢您的评论。在这里适用于 ec2 的真正 policy name 是什么? 执行您的回答后,出现错误。请检查我更新的问题。

以上是关于如何使用 .yaml 文件向 AWS Lambda 函数添​​加策略?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AWS Lambda 向邮递员 POST 请求

如何通过 AWS HTTP API 向 Lambda 发送参数

如何在不使用 SAM 的情况下使用 AWS 代码部署来部署简单的 AWS lambda 函数?

在AWS lambda函数上使用pyspark二进制文件,在向驱动程序发送其端口号之前退出错误Java网关进程

aws lambda 函数可以向专用网​​络中的端点发布帖子吗?

如何使用 GET 请求将参数传递给 AWS Lambda 函数?