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

New Resource: azurerm_cosmosdb_sql_container #3871

Merged
merged 19 commits into from
Aug 18, 2019
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_cosmosdb_cassandra_keyspace": resourceArmCosmosDbCassandraKeyspace(),
"azurerm_cosmosdb_mongo_collection": resourceArmCosmosDbMongoCollection(),
"azurerm_cosmosdb_mongo_database": resourceArmCosmosDbMongoDatabase(),
"azurerm_cosmosdb_sql_container": resourceArmCosmosDbSQLContainer(),
"azurerm_cosmosdb_sql_database": resourceArmCosmosDbSQLDatabase(),
"azurerm_cosmosdb_table": resourceArmCosmosDbTable(),
"azurerm_data_factory": resourceArmDataFactory(),
Expand Down
234 changes: 234 additions & 0 deletions azurerm/resource_arm_cosmosdb_sql_container.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
package azurerm

import (
"fmt"
"log"

"github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2015-04-08/documentdb"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/response"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/validate"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmCosmosDbSQLContainer() *schema.Resource {
return &schema.Resource{
Create: resourceArmCosmosDbSQLContainerCreateUpdate,
Read: resourceArmCosmosDbSQLContainerRead,
Update: resourceArmCosmosDbSQLContainerCreateUpdate,
Delete: resourceArmCosmosDbSQLContainerDelete,

Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},

Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.CosmosEntityName,
},

"resource_group_name": azure.SchemaResourceGroupName(),

"database_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.CosmosEntityName,
},

"account_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.CosmosAccountName,
},

"partition_key_paths": {
Type: schema.TypeString,
Required: false,
Optional: true,
ForceNew: false,
ValidateFunc: validate.NoEmptyStrings,
},

"unique_key_policy": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"unique_keys": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"paths": {
Type: schema.TypeSet,
Required: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
},
},
},
},
},
},
},
}
}

func resourceArmCosmosDbSQLContainerCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmos.DatabaseClient
ctx := meta.(*ArmClient).StopContext

name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
database := d.Get("database_name").(string)
account := d.Get("account_name").(string)
partitionkeypaths := d.Get("partition_key_paths").(string)

if requireResourcesToBeImported && d.IsNewResource() {
existing, err := client.GetSQLContainer(ctx, resourceGroup, account, database, name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Error checking for presence of creating Cosmos SQL Container %s (Account: %s, Database:%s): %+v", name, account, database, err)
}
} else {
id, err := azure.CosmosGetIDFromResponse(existing.Response)
if err != nil {
return fmt.Errorf("Error generating import ID for Cosmos SQL Container '%s' (Account: %s, Database:%s)", name, account, database)
}

return tf.ImportAsExistsError("azurerm_cosmosdb_sql_container", id)
}
}

db := documentdb.SQLContainerCreateUpdateParameters{
SQLContainerCreateUpdateProperties: &documentdb.SQLContainerCreateUpdateProperties{
Resource: &documentdb.SQLContainerResource{
ID: &name,
PartitionKey: &documentdb.ContainerPartitionKey{
Paths: &[]string{partitionkeypaths},
Kind: "Hash",
},
UniqueKeyPolicy: expandSQLContainerUniqueKeyPolicy(d),
},
Options: map[string]*string{},
},
}

future, err := client.CreateUpdateSQLContainer(ctx, resourceGroup, account, database, name, db)
if err != nil {
return fmt.Errorf("Error issuing create/update request for Cosmos SQL Container %s (Account: %s, Database:%s): %+v", name, account, database, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("Error waiting on create/update future for Cosmos SQL Container %s (Account: %s, Database:%s): %+v", name, account, database, err)
}

resp, err := client.GetSQLContainer(ctx, resourceGroup, account, database, name)
if err != nil {
return fmt.Errorf("Error making get request for Cosmos SQL Container %s (Account: %s, Database:%s): %+v", name, account, database, err)
}

id, err := azure.CosmosGetIDFromResponse(resp.Response)
if err != nil {
return fmt.Errorf("Error retrieving the ID for Cosmos SQL Container '%s' (Account: %s, Database:%s) ID: %v", name, account, database, err)
}
d.SetId(id)

return resourceArmCosmosDbSQLContainerRead(d, meta)
}

func resourceArmCosmosDbSQLContainerRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmos.DatabaseClient
ctx := meta.(*ArmClient).StopContext
name := d.Get("name").(string)

id, err := azure.ParseCosmosDatabaseID(d.Id())
if err != nil {
return err
}

resp, err := client.GetSQLContainer(ctx, id.ResourceGroup, id.Account, id.Database, name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[INFO] Error reading Cosmos SQL Container %s (Account %s) - removing from state", id.Database, name)
d.SetId("")
return nil
}

return fmt.Errorf("Error reading Cosmos SQL Container %s (Account %s): %+v", id.Database, name, err)
}

d.Set("resource_group_name", id.ResourceGroup)
d.Set("account_name", id.Account)
d.Set("database_name", id.Database)
if props := resp.SQLContainerProperties; props != nil {
d.Set("name", props.ID)
d.Set("unique_key_policy", props.UniqueKeyPolicy)
d.Set("partition_key_paths", props.PartitionKey)
}

DenheenJ marked this conversation as resolved.
Show resolved Hide resolved
return nil
}

func resourceArmCosmosDbSQLContainerDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmos.DatabaseClient
ctx := meta.(*ArmClient).StopContext
name := d.Get("name").(string)

id, err := azure.ParseCosmosDatabaseID(d.Id())
if err != nil {
return err
}

future, err := client.DeleteSQLContainer(ctx, id.ResourceGroup, id.Account, id.Database, name)
if err != nil {
if !response.WasNotFound(future.Response()) {
return fmt.Errorf("Error deleting Cosmos SQL Container %s (Account %s): %+v", id.Database, name, err)
}
}

err = future.WaitForCompletionRef(ctx, client.Client)
if err != nil {
return fmt.Errorf("Error waiting on delete future for Cosmos SQL Container %s (Account %s): %+v", id.Database, id.Account, err)
}

return nil
}

func expandSQLContainerUniqueKeyPolicy(d *schema.ResourceData) *documentdb.UniqueKeyPolicy {
i := d.Get("unique_key_policy").([]interface{})
var paths []string
if len(i) <= 0 || i[0] == nil {
return nil
}

uniquekeypolicyRaw := i[0].(map[string]interface{})
uniquekeysRaw := uniquekeypolicyRaw["unique_keys"].(*schema.Set).List()
uniquekeyRaw := uniquekeysRaw[0].(map[string]interface{})
pathsRaw := uniquekeyRaw["paths"].(*schema.Set).List()

for _, path := range pathsRaw {
paths = append(paths, path.(string))
}

uniquekey := documentdb.UniqueKey{
Paths: &paths,
}

uniquekeys := make([]documentdb.UniqueKey, 0)
uniquekeys = append(uniquekeys, uniquekey)

output := documentdb.UniqueKeyPolicy{
UniqueKeys: &uniquekeys,
}

return &output
}
120 changes: 120 additions & 0 deletions azurerm/resource_arm_cosmosdb_sql_container_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package azurerm

import (
"fmt"
"net/http"
"testing"

"github.com/Azure/azure-sdk-for-go/services/cosmos-db/mgmt/2015-04-08/documentdb"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func TestAccAzureRMCosmosDbSqlContainer_basic(t *testing.T) {
ri := tf.AccRandTimeInt()
resourceName := "azurerm_cosmosdb_sql_container.test"

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testCheckAzureRMCosmosDbSqlContainerDestroy,
Steps: []resource.TestStep{
{

Config: testAccAzureRMCosmosDbSqlContainer_basic(ri, testLocation()),
Check: resource.ComposeAggregateTestCheckFunc(
testCheckAzureRMCosmosDbSqlContainerExists(resourceName),
),
},
{
ResourceName: resourceName,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testCheckAzureRMCosmosDbSqlContainerDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*ArmClient).cosmos.DatabaseClient
ctx := testAccProvider.Meta().(*ArmClient).StopContext

for _, rs := range s.RootModule().Resources {
if rs.Type != "azurerm_cosmosdb_sql_container" {
continue
}

name := rs.Primary.Attributes["name"]
account := rs.Primary.Attributes["account_name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"]
database := rs.Primary.Attributes["database"]

resp, err := client.GetSQLContainer(ctx, resourceGroup, account, database, name)
if err != nil {
if !utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Bad: Error checking destroy for Cosmos SQL Container %s (account %s) still exists:\n%v", name, account, err)
}
}

if !utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("Cosmos SQL Container %s (account %s) still exists:\n%#v", name, account, resp)
}
}

return nil
}

func testCheckAzureRMCosmosDbSqlContainerExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
client := testAccProvider.Meta().(*ArmClient).cosmos.DatabaseClient
ctx := testAccProvider.Meta().(*ArmClient).StopContext

// Ensure we have enough information in state to look up in API
rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("Not found: %s", resourceName)
}

name := rs.Primary.Attributes["name"]
account := rs.Primary.Attributes["account_name"]
resourceGroup := rs.Primary.Attributes["resource_group_name"]
database := rs.Primary.Attributes["database"]

resp, err := client.GetSQLContainer(ctx, resourceGroup, database, account, name)
if err != nil {
return fmt.Errorf("Bad: Get on cosmosAccountsClient: %+v", err)
}

if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("Bad: Cosmos Container '%s' (account: '%s') does not exist", name, account)
}

return nil
}
}

func testAccAzureRMCosmosDbSqlContainer_basic(rInt int, location string) string {
res := fmt.Sprintf(`
DenheenJ marked this conversation as resolved.
Show resolved Hide resolved
%[1]s

resource "azurerm_cosmosdb_sql_container" "test" {
name = "acctest-%[2]d"
resource_group_name = "${azurerm_cosmosdb_account.test.resource_group_name}"
account_name = "${azurerm_cosmosdb_account.test.name}"
database_name = "${azurerm_cosmosdb_sql_database.test.name}"
partition_key_paths = "/definition/id"
unique_key_policy {
unique_keys {
paths = ["/definition/idlong", "/definition/idshort"]
}

}
}


`, testAccAzureRMCosmosDBAccount_basic(rInt, location, string(documentdb.Eventual), "", ""), rInt)
fmt.Print(res)
return res
}
2 changes: 1 addition & 1 deletion scripts/gofmtcheck.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ if [ -n "${gofmt_files}" ]; then
exit 1
fi

exit 0
exit 0
Loading