title: How to add a resource based policy to a Lambda function created using AWS SAM via AWS CDK?
body: <p>I am using CDK to create AWS SAM functions using the following code:</p>
  <pre class="lang-py prettyprint-override"><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(&quot;arn:aws:iam::111111111111:role/rolename&quot;)
  
  app = core.App()
  stack = core.Stack(app, &quot;cdk-test&quot;)
  
  fn = CfnFunction(
      stack,
      id=f&quot;CfnFn{str(random.randrange(1000, 1000000))}&quot;,
      **{
          &quot;handler&quot;: &quot;handler&quot;,
          &quot;runtime&quot;: &quot;python3.8&quot;,
          &quot;memory_size&quot;: 256,
          &quot;timeout&quot;: 10,
          &quot;code_uri&quot;: &quot;code_uri&quot;
      }
  )
  
  
  app.synth()
  
  </code></pre>
  <p>I would like to invoke the Lambda function from another account, and would like to do this by attaching a <a href="https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html" rel="nofollow noreferrer">resource based policy</a>.</p>
  <p>This is easily achievable using <code>aws_cdk.aws_lambda.Function</code> itself by calling the <a href="https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_lambda/Function.html#aws_cdk.aws_lambda.Function.add_permission" rel="nofollow noreferrer"><code>add_permission</code></a> method.</p>
  <p>However, <a href="https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_sam/CfnFunction.html" rel="nofollow noreferrer"><code>aws_cdk.aws_sam.CfnFunction</code></a> does not have an <code>add_permission</code> 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.</p>