简体   繁体   中英

How to add a resource based policy to a Lambda function created using AWS SAM via AWS CDK?

I am using CDK to create AWS SAM functions using the following code:

#!/usr/bin/env python3

from aws_cdk import core

from aws_cdk.aws_sam import CfnFunction
from aws_cdk.aws_iam import PolicyStatement, ServicePrincipal, PolicyDocument, Policy

import random

principal = ServicePrincipal("arn:aws:iam::111111111111:role/rolename")

app = core.App()
stack = core.Stack(app, "cdk-test")

fn = CfnFunction(
    stack,
    id=f"CfnFn{str(random.randrange(1000, 1000000))}",
    **{
        "handler": "handler",
        "runtime": "python3.8",
        "memory_size": 256,
        "timeout": 10,
        "code_uri": "code_uri"
    }
)


app.synth()

I would like to invoke the Lambda function from another account, and would like to do this by attaching a resource based policy .

This is easily achievable using aws_cdk.aws_lambda.Function itself by calling the add_permission method.

However, aws_cdk.aws_sam.CfnFunction does not have an add_permission method. Is there an another way to achieve this using SAM (with CDK)? Or should I just leave SAM behind and switch to creating Lambda's directly.

This can be done achieved with the help of AWS::Lambda::Permission using aws_cdk.aws_lambda.CfnPermission .

from aws_cdk import aws_lambda

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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