Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 743
rohithpr Avatar asked Oct 16 '25 11:10

rohithpr


1 Answers

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",
)
like image 175
rohithpr Avatar answered Oct 19 '25 00:10

rohithpr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!