Add inline policy to aws SAM template
Asked Answered
F

1

9

I'm using SAM Template to create my serverless application.

Using the tag Policies under the properties of the resource I can add standard policies like this:

Resources:
  QueryFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: query/
      Handler: app.lambda_handler
      Policies:
        - AmazonDynamoDBFullAccess
        - AWSLambdaVPCAccessExecutionRole
      Runtime: python3.7

The problem is that I need to attach an inline policy to access only a specific DynamoDB table.

How can i put this inline policy in the template?

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "dynamodb:*",
            "Resource": "dynamo_db_table_endpoint"
        }
    ]
}

Thanks

Faunus answered 9/12, 2019 at 13:15 Comment(0)
P
21

Try this:

QueryFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: query/
      Handler: app.lambda_handler
      Policies:
        - AmazonDynamoDBFullAccess
        - AWSLambdaVPCAccessExecutionRole
        - Version: '2012-10-17' # Policy Document
          Statement:
            - Effect: Allow
              Action:
                - dynamodb:*
              Resource: 'arn:aws:dynamodb:*:*:table/dynamo_db_table_endpoint'
      Runtime: python3.7

Amazon DynamoDB: Allows Access to a Specific Table

If you would like to pass your tableName as parameter change Resource: 'arn:aws:dynamodb:*:*:table/dynamo_db_table_endpoint' to Resource: !Sub 'arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}'

Hope this helps

Pitsaw answered 9/12, 2019 at 13:42 Comment(6)
@Faunus any luck with that?Pitsaw
Can we add multiple resources in this? ex: Resource: [<arn1>,<arn2>]Eld
I'm aware i'm adding to this a year late, but can you only attach the PolicyDocument section or is there a way to build a Policy that adds existing Roles too? e.g. The final example on this page: docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/…Satirical
this isnt working for me in 2023... something changed?Markhor
@AriWaisberg did you find a solution to this? I can confirm it's not working for me either as of May 2023.Lyrate
@AriWaisberg can you explain that approach of commands please? I desire to follow that approach, but for now did not understand you comment.Tewfik

© 2022 - 2024 — McMap. All rights reserved.