简体   繁体   English

如何使用 AWS SAM 将基于资源的策略添加到 lambda

[英]How to add a resource based policy to a lambda using AWS SAM

I want to create a deployment script for some lambda functions using AWS SAM.我想使用 AWS SAM 为一些 lambda 函数创建一个部署脚本。 Two of those functions will be deployed into one account(account A) but will be triggered by an s3 bucket object creation event in a second account(account B).其中两个功能将部署到一个账户(账户 A)中,但将由第二个账户(账户 B)中的 s3 存储桶 object 创建事件触发。 From what I know the only way to do this is by using adding a resource based policy to my lambda.据我所知,唯一的方法是向我的 lambda 添加基于资源的策略。 But I don't know how to do that in AWS SAM.但我不知道如何在 AWS SAM 中做到这一点。 My current yaml file looks like this.我当前的 yaml 文件看起来像这样。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  deploy-test-s3-triggered-lambda

Parameters:
  AppBucketName:
    Type: String
    Description: "REQUIRED: Unique S3 bucket name to use for the app."

Resources:
  S3TriggeredLambda:
    Type: AWS::Serverless::Function
    Properties: 
      Role: arn:aws:iam::************:role/lambda-s3-role
      Handler: src/handlers/s3-triggered-lambda.invokeAPI
      CodeUri: src/handlers/s3-triggered-lambda.js.zip
      Runtime: nodejs10.x
      MemorySize: 128
      Timeout: 60
      Policies:
        S3ReadPolicy:
          BucketName: !Ref AppBucketName
      Events:
        S3NewObjectEvent:
          Type: S3
          Properties:
            Bucket: !Ref AppBucket
            Events: s3:ObjectCreated:*
  AppBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref AppBucketName

What do I need to add to this yaml file in order to tie a resource based policy that allows for cross account access to my lambda function?我需要在此 yaml 文件中添加什么以绑定基于资源的策略,该策略允许跨账户访问我的 lambda function?

This can be done achieved with the help of AWS::Lambda::Permission using aws_cdk.aws_lambda.CfnPermission .这可以在AWS::Lambda::Permission的帮助下使用aws_cdk.aws_lambda.CfnPermission来实现。

For example, to allow your lambda to be called from a role in another account, add the following to your CDK:例如,要允许从另一个帐户中的角色调用您的 lambda,请将以下内容添加到您的 CDK:

from aws_cdk import aws_lambda

aws_lambda.CfnPermission(
    scope,
    "CrossAccountInvocationPermission",
    action="lambda:InvokeFunction",
    function_name="FunctionName",
    principal="arn:aws:iam::111111111111:role/rolename",
)

If your bucket and your Lambda function exist in separate accounts I don't know if it's possible to modify both of them from SAM / a single CloudFormation template.如果您的存储桶和您的 Lambda function 存在于不同的帐户中,我不知道是否可以从 SAM/单个 CloudFormation 模板修改它们。

Don't think cross account s3 event is possible with SAM, may need to go back to CFN.不要认为 SAM 可能发生跨账户 s3 事件,可能需要将 go 回传给 CFN。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM