rohithpr
rohithpr

Reputation: 6330

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.

Upvotes: 4

Views: 3361

Answers (1)

rohithpr
rohithpr

Reputation: 6330

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",
)

Upvotes: 5

Related Questions