Skip to content

Commit

Permalink
Adds validation for ttl subfields
Browse files Browse the repository at this point in the history
  • Loading branch information
gdavison committed Jun 14, 2024
1 parent fec28bc commit 9f4eafb
Show file tree
Hide file tree
Showing 2 changed files with 196 additions and 1 deletion.
70 changes: 69 additions & 1 deletion internal/service/dynamodb/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
awstypes "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
"github.com/hashicorp/aws-sdk-go-base/v2/tfawserr"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
Expand Down Expand Up @@ -116,6 +117,7 @@ func resourceTable() *schema.Resource {
// https://github.com/hashicorp/terraform-provider-aws/issues/25214
return old.(string) != new.(string) && new.(string) != ""
}),
validateTTLCustomDiff,
verify.SetTagsDiff,
),

Expand Down Expand Up @@ -450,7 +452,7 @@ func resourceTable() *schema.Resource {
Schema: map[string]*schema.Schema{
"attribute_name": {
Type: schema.TypeString,
Required: true,
Optional: true,
},
names.AttrEnabled: {
Type: schema.TypeBool,
Expand Down Expand Up @@ -2389,3 +2391,69 @@ func validateProvisionedThroughputField(diff *schema.ResourceDiff, key string) e
}
return nil
}

func validateTTLCustomDiff(ctx context.Context, d *schema.ResourceDiff, meta any) error {
var diags diag.Diagnostics

configRaw := d.GetRawConfig()
if !configRaw.IsKnown() || configRaw.IsNull() {
return nil
}

ttlPath := cty.GetAttrPath("ttl")
ttl := configRaw.GetAttr("ttl")
if ttl.IsKnown() && !ttl.IsNull() {
listenerActionsPlantimeValidate(ttlPath, ttl, &diags)
}

return sdkdiag.DiagnosticsError(diags)
}

func listenerActionsPlantimeValidate(ttlPath cty.Path, ttl cty.Value, diags *diag.Diagnostics) {
it := ttl.ElementIterator()
for it.Next() {
i, action := it.Element()
ttlPath := ttlPath.Index(i)

listenerActionPlantimeValidate(ttlPath, action, diags)
}
}

func listenerActionPlantimeValidate(ttlPath cty.Path, ttl cty.Value, diags *diag.Diagnostics) {
attribute := ttl.GetAttr("attribute_name")
if !attribute.IsKnown() {
return
}

enabled := ttl.GetAttr(names.AttrEnabled)
if !enabled.IsKnown() {
return
}
if enabled.IsNull() {
return
}

if enabled.True() {
if attribute.IsNull() {
*diags = append(*diags, errs.NewAttributeRequiredWhenError(
ttlPath.GetAttr("attribute_name"),
ttlPath.GetAttr(names.AttrEnabled),
"true",
))
} else if attribute.AsString() == "" {
*diags = append(*diags, errs.NewInvalidValueAttributeErrorf(
ttlPath.GetAttr("attribute_name"),
"Attribute %q cannot have an empty value",
errs.PathString(ttlPath.GetAttr("attribute_name")),
))
}
} else {
if !(attribute.IsNull() || attribute.AsString() == "") {
*diags = append(*diags, errs.NewAttributeConflictsWhenError(
ttlPath.GetAttr("attribute_name"),
ttlPath.GetAttr(names.AttrEnabled),
"false",
))
}
}
}
127 changes: 127 additions & 0 deletions internal/service/dynamodb/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1374,6 +1374,11 @@ func TestAccDynamoDBTable_TTL_enabled(t *testing.T) {
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccTableConfig_timeToLive_unset(rName),
PlanOnly: true,
ExpectNonEmptyPlan: false,
},
},
})
}
Expand Down Expand Up @@ -1405,18 +1410,82 @@ func TestAccDynamoDBTable_TTL_disabled(t *testing.T) {
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccTableConfig_timeToLive_unset(rName),
PlanOnly: true,
ExpectNonEmptyPlan: false,
},
},
})
}

// TTL tests must be split since it can only be updated once per hour
// ValidationException: Time to live has been modified multiple times within a fixed interval
func TestAccDynamoDBTable_TTL_update(t *testing.T) {
ctx := acctest.Context(t)
var table awstypes.TableDescription
resourceName := "aws_dynamodb_table.test"
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(ctx, t) },
ErrorCheck: acctest.ErrorCheck(t, names.DynamoDBServiceID),
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
CheckDestroy: testAccCheckTableDestroy(ctx),
Steps: []resource.TestStep{
{
Config: testAccTableConfig_timeToLive(rName, false),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckInitialTableExists(ctx, resourceName, &table),
resource.TestCheckResourceAttr(resourceName, "ttl.#", acctest.Ct1),
resource.TestCheckResourceAttr(resourceName, "ttl.0.attribute_name", ""),
resource.TestCheckResourceAttr(resourceName, "ttl.0.enabled", acctest.CtFalse),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
{
Config: testAccTableConfig_timeToLive(rName, true),
Check: resource.ComposeAggregateTestCheckFunc(
testAccCheckInitialTableExists(ctx, resourceName, &table),
resource.TestCheckResourceAttr(resourceName, "ttl.#", acctest.Ct1),
resource.TestCheckResourceAttr(resourceName, "ttl.0.attribute_name", "TestTTL"),
resource.TestCheckResourceAttr(resourceName, "ttl.0.enabled", acctest.CtTrue),
),
},
},
})
}

func TestAccDynamoDBTable_TTL_validate(t *testing.T) {
ctx := acctest.Context(t)
rName := sdkacctest.RandomWithPrefix(acctest.ResourcePrefix)

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acctest.PreCheck(ctx, t) },
ErrorCheck: acctest.ErrorCheck(t, names.DynamoDBServiceID),
ProtoV5ProviderFactories: acctest.ProtoV5ProviderFactories,
CheckDestroy: testAccCheckTableDestroy(ctx),
Steps: []resource.TestStep{
{
Config: testAccTableConfig_timeToLive_AttributeName(rName, "TestTTL", false),
ExpectError: regexache.MustCompile(regexp.QuoteMeta(`Attribute "ttl[0].attribute_name" cannot be specified when "ttl[0].enabled" is "false"`)),
},
{
Config: testAccTableConfig_timeToLive_AttributeName(rName, "", true),
ExpectError: regexache.MustCompile(regexp.QuoteMeta(`Attribute "ttl[0].attribute_name" cannot have an empty value`)),
},
{
Config: testAccTableConfig_TTL_missingAttributeName(rName, true),
ExpectError: regexache.MustCompile(regexp.QuoteMeta(`Attribute "ttl[0].attribute_name" cannot have an empty value`)),
},
},
})
}

func TestAccDynamoDBTable_attributeUpdate(t *testing.T) {
ctx := acctest.Context(t)
if testing.Short() {
Expand Down Expand Up @@ -3517,6 +3586,64 @@ resource "aws_dynamodb_table" "test" {
`, rName, ttlEnabled)
}

func testAccTableConfig_timeToLive_unset(rName string) string {
return fmt.Sprintf(`
resource "aws_dynamodb_table" "test" {
hash_key = "TestTableHashKey"
name = %[1]q
read_capacity = 1
write_capacity = 1
attribute {
name = "TestTableHashKey"
type = "S"
}
}
`, rName)
}

func testAccTableConfig_timeToLive_AttributeName(rName, ttlAttribute string, ttlEnabled bool) string {
return fmt.Sprintf(`
resource "aws_dynamodb_table" "test" {
hash_key = "TestTableHashKey"
name = %[1]q
read_capacity = 1
write_capacity = 1
attribute {
name = "TestTableHashKey"
type = "S"
}
ttl {
attribute_name = %[2]q
enabled = %[3]t
}
}
`, rName, ttlAttribute, ttlEnabled)
}

func testAccTableConfig_TTL_missingAttributeName(rName string, ttlEnabled bool) string {
return fmt.Sprintf(`
resource "aws_dynamodb_table" "test" {
hash_key = "TestTableHashKey"
name = %[1]q
read_capacity = 1
write_capacity = 1
attribute {
name = "TestTableHashKey"
type = "S"
}
ttl {
attribute_name = ""
enabled = %[2]t
}
}
`, rName, ttlEnabled)
}

func testAccTableConfig_oneAttribute(rName, hashKey, attrName, attrType string) string {
return fmt.Sprintf(`
resource "aws_dynamodb_table" "test" {
Expand Down

0 comments on commit 9f4eafb

Please sign in to comment.