Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cosmosdb_mongo_collection - support index & system_index #6426

Merged
merged 15 commits into from Apr 21, 2020
Merged
Expand Up @@ -82,6 +82,26 @@ func resourceArmCosmosDbMongoCollection() *schema.Resource {
Computed: true,
ValidateFunc: validate.CosmosThroughput,
},

"index": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"keys": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},

"unique": {
Type: schema.TypeBool,
Optional: true,
Default: true,
},
},
},
},
},
}
}
Expand Down Expand Up @@ -121,7 +141,7 @@ func resourceArmCosmosDbMongoCollectionCreate(d *schema.ResourceData, meta inter
MongoDBCollectionCreateUpdateProperties: &documentdb.MongoDBCollectionCreateUpdateProperties{
Resource: &documentdb.MongoDBCollectionResource{
ID: &name,
Indexes: expandCosmosMongoCollectionIndexes(ttl),
Indexes: expandCosmosMongoCollectionIndex(d.Get("index").(*schema.Set).List(), ttl),
},
Options: map[string]*string{},
},
Expand Down Expand Up @@ -181,7 +201,7 @@ func resourceArmCosmosDbMongoCollectionUpdate(d *schema.ResourceData, meta inter
MongoDBCollectionCreateUpdateProperties: &documentdb.MongoDBCollectionCreateUpdateProperties{
Resource: &documentdb.MongoDBCollectionResource{
ID: &id.Collection,
Indexes: expandCosmosMongoCollectionIndexes(ttl),
Indexes: expandCosmosMongoCollectionIndex(d.Get("index").(*schema.Set).List(), ttl),
},
Options: map[string]*string{},
},
Expand Down Expand Up @@ -264,7 +284,9 @@ func resourceArmCosmosDbMongoCollectionRead(d *schema.ResourceData, meta interfa
}

if props.Indexes != nil {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to ensure these fields are always set, so we can remove the if statement here, since the flatten function should handle these being nil

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

d.Set("default_ttl_seconds", flattenCosmosMongoCollectionIndexes(props.Indexes))
if err := d.Set("default_ttl_seconds", flattenCosmosMongoCollectionIndex(props.Indexes)); err != nil {
return fmt.Errorf("failed to set `default_ttl_seconds`: %+v", err)
}
}
}

Expand Down Expand Up @@ -307,11 +329,26 @@ func resourceArmCosmosDbMongoCollectionDelete(d *schema.ResourceData, meta inter
return nil
}

func expandCosmosMongoCollectionIndexes(defaultTtl *int) *[]documentdb.MongoIndex {
outputs := make([]documentdb.MongoIndex, 0)
func expandCosmosMongoCollectionIndex(indexes []interface{}, defaultTtl *int) *[]documentdb.MongoIndex {
results := make([]documentdb.MongoIndex, 0)

if len(indexes) != 0 {
for _, v := range indexes {
index := v.(map[string]interface{})

results = append(results, documentdb.MongoIndex{
Key: &documentdb.MongoIndexKeys{
Keys: utils.ExpandStringSlice(index["keys"].(*schema.Set).List()),
},
Options: &documentdb.MongoIndexOptions{
Unique: utils.Bool(index["unique"].(bool)),
},
})
}
}

if defaultTtl != nil {
outputs = append(outputs, documentdb.MongoIndex{
results = append(results, documentdb.MongoIndex{
Key: &documentdb.MongoIndexKeys{
Keys: &[]string{"_ts"},
},
Expand All @@ -321,24 +358,19 @@ func expandCosmosMongoCollectionIndexes(defaultTtl *int) *[]documentdb.MongoInde
})
}

return &outputs
return &results
}

func flattenCosmosMongoCollectionIndexes(indexes *[]documentdb.MongoIndex) *int {
var ttl int
for _, i := range *indexes {
if key := i.Key; key != nil {
var ttlInner int32

if keys := key.Keys; keys != nil && len(*keys) > 0 {
k := (*keys)[0]

if k == "_ts" {
ttl = int(ttlInner)
}
func flattenCosmosMongoCollectionIndex(input *[]documentdb.MongoIndex) *int32 {
var ttl *int32
for _, v := range *input {
if v.Key != nil && v.Key.Keys != nil {
key := (*v.Key.Keys)[0]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there's a crash here if there's 0 items in this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

if key == "_ts" && v.Options != nil && v.Options.ExpireAfterSeconds != nil {
ttl = v.Options.ExpireAfterSeconds
}
}
}

return &ttl
return ttl
}
Expand Up @@ -121,6 +121,28 @@ func TestAccAzureRMCosmosDbMongoCollection_throughput(t *testing.T) {
})
}

func TestAccAzureRMCosmosDbMongoCollection_withIndex(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_cosmosdb_mongo_collection", "test")

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { acceptance.PreCheck(t) },
Providers: acceptance.SupportedProviders,
CheckDestroy: testCheckAzureRMCosmosDbMongoCollectionDestroy,
Steps: []resource.TestStep{
{
Config: testAccAzureRMCosmosDbMongoCollection_withIndex(data),
Check: resource.ComposeAggregateTestCheckFunc(
testCheckAzureRMCosmosDbMongoCollectionExists(data.ResourceName),
resource.TestCheckResourceAttr(data.ResourceName, "default_ttl_seconds", "707"),
resource.TestCheckResourceAttr(data.ResourceName, "index.#", "3"),
),
},
// Service API would return additional system indexes aside from user specified indexes. So index needs to be ignored. Otherwise, it would occur diff.
data.ImportStep("index"),
},
})
}

func testCheckAzureRMCosmosDbMongoCollectionDestroy(s *terraform.State) error {
client := acceptance.AzureProvider.Meta().(*clients.Client).Cosmos.DatabaseClient
ctx := acceptance.AzureProvider.Meta().(*clients.Client).StopContext
Expand Down Expand Up @@ -238,3 +260,32 @@ resource "azurerm_cosmosdb_mongo_collection" "test" {
}
`, testAccAzureRMCosmosDbMongoDatabase_basic(data), data.RandomInteger, throughput)
}

func testAccAzureRMCosmosDbMongoCollection_withIndex(data acceptance.TestData) string {
return fmt.Sprintf(`
%[1]s

resource "azurerm_cosmosdb_mongo_collection" "test" {
name = "acctest-%[2]d"
resource_group_name = azurerm_cosmosdb_mongo_database.test.resource_group_name
account_name = azurerm_cosmosdb_mongo_database.test.account_name
database_name = azurerm_cosmosdb_mongo_database.test.name
default_ttl_seconds = 707
throughput = 400

index {
keys = ["seven", "six"]
unique = true
}

index {
keys = ["day"]
unique = false
}

index {
keys = ["month"]
}
}
`, testAccAzureRMCosmosDbMongoDatabase_basic(data), data.RandomInteger)
}
9 changes: 9 additions & 0 deletions website/docs/r/cosmosdb_mongo_collection.html.markdown
Expand Up @@ -45,8 +45,17 @@ The following arguments are supported:
* `database_name` - (Required) The name of the Cosmos DB Mongo Database in which the Cosmos DB Mongo Collection is created. Changing this forces a new resource to be created.
* `default_ttl_seconds` - (Required) The default Time To Live in seconds. If the value is `0` items are not automatically expired.
* `shard_key` - (Required) The name of the key to partition on for sharding. There must not be any other unique index keys.
* `index` - (Optional) One or more `index` blocks as defined below.
* `throughput` - (Optional) The throughput of the MongoDB collection (RU/s). Must be set in increments of `100`. The minimum value is `400`. This must be set upon database creation otherwise it cannot be updated without a manual terraform destroy-apply.

---

The `index` block supports the following:

* `keys` - (Required) Specifies the set of keys for each Cosmos DB Mongo Collection.

* `unique` - (Optional) Is the index unique or not? Defaults to `true`.

## Attributes Reference

The following attributes are exported:
Expand Down