0
votes

I'm trying to create an AWS Role which prevents CloudFormation delete a table. For instance, I created my table as follows:

UsersDynamoDBTable:
    Type: AWS::DynamoDB::Table
    Description: Users DynamoDB Table
    Properties:
      AttributeDefinitions:
        - AttributeName: hashKey
          AttributeType: S
        - AttributeName: rangeKey
          AttributeType: S
      KeySchema:
        - AttributeName: hashKey
          KeyType: HASH
        - AttributeName: rangeKey
          KeyType: RANGE
      BillingMode: PAY_PER_REQUEST
      GlobalSecondaryIndexes:
        - IndexName: index-rangeKey
          KeySchema:
            - AttributeName: rangeKey
              KeyType: HASH
            - AttributeName: hashKey
              KeyType: RANGE
          Projection:
            ProjectionType: ALL

Now suppose that a develop accidentally delete this lines and update stack. This way the table with all its data would be removed. So I'd like to create a role which prevents CloudFormation delete DynamoDB tables. My first attempt was creating the Role below, but it didn't work.

PreventCloudFormationDeleteTableIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - cloudformation.amazonaws.com
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: PreventTableDeletePolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Deny
                Action:
                  - dynamodb:DeleteTable
                Resource:
                  - !Join
                    - '/'
                    - - !Join [':', ['arn:aws:dynamodb', !Sub '${AWS::Region}', '*', 'table']]
                      - !Join ['', [!Sub '${StackName}', '*']]

Am I missing some Role configuration?

Thank you.

2
How did you use this role? Did you pass it in when you created the stack?cementblocks
Yes. I passed it on the same template I create the tablesPedro Arantes
When you create a stack you can specify a role arn for cloudformation to use when creating/updating/deleting resources. That role cannot of course be created by the stack.cementblocks

2 Answers

7
votes

You can use a DeletionPolicy of RETAIN to prevent the table from being deleted when the stack is removed or table is removed from the template. Also the new UpdateReplacePolicy will prevent CloudFormation from deleting the table when it needs to do so due to primary key changes.

2
votes

Considering that the role is properly attached to the invoking user/principal, is it possible that the policy Arn from that join does not match the table Arn?

Also consider retaining the resource instead of denying the operation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-deletionpolicy.html