Repository: aws-cloudformation/cfn-lint

Issue:
Feature request: Check for mutual exclusive attributes for DynamoDB capacity
Currently you can specify provisioned capacity and `BillingMode: PAY_PER_REQUEST` for a DynamoDB table and CloudFormation will process the resource without errors. In that case the provisioned capacity settings are prioritized over the billing mode, resulting in the table still being set to `BillingMode: PROVISIONED`.

I propose that `cfn-lint` checks that  `BillingMode: PAY_PER_REQUEST` and provisioned capacity on a table and its global indexes are mutually exclusive.


Discussion:
Ran into a similar issue myself, so I am currently writing the supporting code. Hope to have a PR this week for this.
@cmmeyer this seems like a weird one.  I'm going to put this one as an Error and you can debate me later on it.  Error not because it will fail but it won't do what you ask it to do.

Resolving patch:
diff --git a/src/cfnlint/rules/resources/dynamodb/BillingMode.py b/src/cfnlint/rules/resources/dynamodb/BillingMode.py
new file mode 100644
--- /dev/null
+++ b/src/cfnlint/rules/resources/dynamodb/BillingMode.py
@@ -0,0 +1,65 @@
+"""
+  Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy of this
+  software and associated documentation files (the "Software"), to deal in the Software
+  without restriction, including without limitation the rights to use, copy, modify,
+  merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
+  permit persons to whom the Software is furnished to do so.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+"""
+from cfnlint import CloudFormationLintRule
+from cfnlint import RuleMatch
+
+
+class BillingMode(CloudFormationLintRule):
+    """Check DynamoDB BillingMode Configuration"""
+    id = 'E3024'
+    shortdesc = 'Validate that ProvisionedThroughput is not specified with BillingMode PAY_PER_REQUEST'
+    description = 'When using ProvisionedThroughput with BillingMode PAY_PER_REQUEST will result in ' \
+                  'BillingMode being changed to PROVISIONED'
+    source_url = 'https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html'
+    tags = ['resources', 'dynamodb', 'provisioned_throughput', 'billing_mode']
+
+    def __init__(self):
+        """Init"""
+        super(BillingMode, self).__init__()
+        self.resource_property_types = ['AWS::DynamoDB::Table']
+
+    def check(self, properties, path, cfn):
+        """Check itself"""
+        matches = []
+        property_sets = cfn.get_object_without_conditions(properties)
+        for property_set in property_sets:
+            billing_mode = property_set.get('Object').get('BillingMode')
+            if billing_mode == 'PAY_PER_REQUEST':
+                if 'ProvisionedThroughput' in property_set.get('Object'):
+                    if property_set['Scenario'] is None:
+                        message = '"ProvisionedThroughput" must not be specified when BillingMode is set to "PAY_PER_REQUEST" at {0}'
+                        matches.append(RuleMatch(
+                            path,
+                            message.format('/'.join(map(str, path)))
+                        ))
+                    else:
+                        scenario_text = ' and '.join(['when condition "%s" is %s' % (k, v) for (k, v) in property_set['Scenario'].items()])
+                        message = '"ProvisionedThroughput" must not be specified when BillingMode is set to "PAY_PER_REQUEST" {0} at {1}'
+                        matches.append(RuleMatch(
+                            path,
+                            message.format(scenario_text, '/'.join(map(str, path)))
+                        ))
+
+        return matches
+
+    def match_resource_properties(self, properties, _, path, cfn):
+        """Match for sub properties"""
+        matches = []
+
+        matches.extend(self.check(properties, path, cfn))
+
+        return matches


Test patch:
diff --git a/test/fixtures/templates/bad/resources/dynamodb/billing_mode.yaml b/test/fixtures/templates/bad/resources/dynamodb/billing_mode.yaml
new file mode 100644
--- /dev/null
+++ b/test/fixtures/templates/bad/resources/dynamodb/billing_mode.yaml
@@ -0,0 +1,43 @@
+---
+AWSTemplateFormatVersion: "2010-09-09"
+Conditions:
+  cIsPrimaryRegion: !Equals ['us-east-1', !Ref 'AWS::Region']
+Resources:
+  DynamoDb:
+    Type: "AWS::DynamoDB::Table"
+    Properties:
+      KeySchema:
+      -
+        AttributeName: String
+        KeyType: String
+      BillingMode: PAY_PER_REQUEST
+      ProvisionedThroughput:
+        WriteCapacityUnits: 1
+        ReadCapacityUnits: 1
+  DynamoDbConditioned:
+    Type: "AWS::DynamoDB::Table"
+    Properties:
+      KeySchema:
+      -
+        AttributeName: String
+        KeyType: String
+      BillingMode: !If [cIsPrimaryRegion, PAY_PER_REQUEST, PROVISIONED]
+      ProvisionedThroughput:
+        Fn::If:
+        - cIsPrimaryRegion
+        - WriteCapacityUnits: 1
+          ReadCapacityUnits: 1
+        - WriteCapacityUnits: 1
+          ReadCapacityUnits: 1
+  # This shouldn't fail but probably will for for now
+  DynamoDbConditionedDeep:
+    Type: "AWS::DynamoDB::Table"
+    Properties:
+      KeySchema:
+      -
+        AttributeName: String
+        KeyType: String
+      BillingMode: !If [cIsPrimaryRegion, PAY_PER_REQUEST, PROVISIONED]
+      ProvisionedThroughput:
+        WriteCapacityUnits: !If [cIsPrimaryRegion, !Ref 'AWS::NoValue', 1]
+        ReadCapacityUnits: !If [cIsPrimaryRegion, !Ref 'AWS::NoValue', 1]
diff --git a/test/fixtures/templates/good/resources/dynamodb/billing_mode.yaml b/test/fixtures/templates/good/resources/dynamodb/billing_mode.yaml
new file mode 100644
--- /dev/null
+++ b/test/fixtures/templates/good/resources/dynamodb/billing_mode.yaml
@@ -0,0 +1,28 @@
+---
+AWSTemplateFormatVersion: "2010-09-09"
+Conditions:
+  cIsPrimaryRegion: !Equals ['us-east-1', !Ref 'AWS::Region']
+Resources:
+  DynamoDb:
+    Type: "AWS::DynamoDB::Table"
+    Properties:
+      KeySchema:
+      -
+        AttributeName: String
+        KeyType: String
+      BillingMode: PAY_PER_REQUEST
+  DynamoDbConditioned:
+    Type: "AWS::DynamoDB::Table"
+    Properties:
+      KeySchema:
+      -
+        AttributeName: String
+        KeyType: String
+      BillingMode: !If [cIsPrimaryRegion, PAY_PER_REQUEST, PROVISIONED]
+      ProvisionedThroughput:
+        Fn::If:
+        - cIsPrimaryRegion
+        - !Ref "AWS::NoValue"
+        - WriteCapacityUnits: 1
+          ReadCapacityUnits: 1
+  
diff --git a/test/rules/resources/dynamodb/test_billing_mode.py b/test/rules/resources/dynamodb/test_billing_mode.py
new file mode 100644
--- /dev/null
+++ b/test/rules/resources/dynamodb/test_billing_mode.py
@@ -0,0 +1,37 @@
+"""
+  Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+
+  Permission is hereby granted, free of charge, to any person obtaining a copy of this
+  software and associated documentation files (the "Software"), to deal in the Software
+  without restriction, including without limitation the rights to use, copy, modify,
+  merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
+  permit persons to whom the Software is furnished to do so.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+  PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+"""
+from cfnlint.rules.resources.dynamodb.BillingMode import BillingMode  # pylint: disable=E0401
+from ... import BaseRuleTestCase
+
+
+class TestBillingMode(BaseRuleTestCase):
+    """Test BillingMode"""
+    def setUp(self):
+        """Setup"""
+        super(TestBillingMode, self).setUp()
+        self.collection.register(BillingMode())
+        self.success_templates = [
+            'test/fixtures/templates/good/resources/dynamodb/billing_mode.yaml'
+        ]
+
+    def test_file_positive(self):
+        """Test Positive"""
+        self.helper_file_positive()
+
+    def test_file_negative_alias(self):
+        """Test failure"""
+        self.helper_file_negative('test/fixtures/templates/bad/resources/dynamodb/billing_mode.yaml', 3)