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

Add cosmos db/keyspace/table resources #3442

Merged
merged 25 commits into from
May 16, 2019
Merged
Show file tree
Hide file tree
Changes from all 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
12 changes: 6 additions & 6 deletions azurerm/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ type ArmClient struct {

StopContext context.Context

cosmosDBClient documentdb.DatabaseAccountsClient
cosmosAccountsClient documentdb.DatabaseAccountsClient

automationAccountClient automation.AccountClient
automationAgentRegistrationInfoClient automation.AgentRegistrationInformationClient
Expand Down Expand Up @@ -498,7 +498,7 @@ func getArmClient(c *authentication.Config, skipProviderRegistration bool, partn
client.registerContainerInstanceClients(endpoint, c.SubscriptionID, auth)
client.registerContainerRegistryClients(endpoint, c.SubscriptionID, auth)
client.registerContainerServicesClients(endpoint, c.SubscriptionID, auth)
client.registerCosmosDBClients(endpoint, c.SubscriptionID, auth)
client.registerCosmosAccountsClients(endpoint, c.SubscriptionID, auth)
client.registerDatabricksClients(endpoint, c.SubscriptionID, auth)
client.registerDatabases(endpoint, c.SubscriptionID, auth, sender)
client.registerDataFactoryClients(endpoint, c.SubscriptionID, auth)
Expand Down Expand Up @@ -735,10 +735,10 @@ func (c *ArmClient) registerCognitiveServiceClients(endpoint, subscriptionId str
c.cognitiveAccountsClient = accountsClient
}

func (c *ArmClient) registerCosmosDBClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
cdb := documentdb.NewDatabaseAccountsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&cdb.Client, auth)
c.cosmosDBClient = cdb
func (c *ArmClient) registerCosmosAccountsClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
ca := documentdb.NewDatabaseAccountsClientWithBaseURI(endpoint, subscriptionId)
c.configureClient(&ca.Client, auth)
c.cosmosAccountsClient = ca
}

func (c *ArmClient) registerMediaServiceClients(endpoint, subscriptionId string, auth autorest.Authorizer) {
Expand Down
8 changes: 4 additions & 4 deletions azurerm/data_source_cosmos_db_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import (
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func dataSourceArmCosmosDBAccount() *schema.Resource {
func dataSourceArmCosmosDbAccount() *schema.Resource {
return &schema.Resource{
Read: dataSourceArmCosmosDBAccountRead,
Read: dataSourceArmCosmosDbAccountRead,

Schema: map[string]*schema.Schema{
"name": {
Expand Down Expand Up @@ -176,8 +176,8 @@ func dataSourceArmCosmosDBAccount() *schema.Resource {
}
}

func dataSourceArmCosmosDBAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosDBClient
func dataSourceArmCosmosDbAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosAccountsClient
ctx := meta.(*ArmClient).StopContext

resourceGroup := d.Get("resource_group_name").(string)
Expand Down
128 changes: 128 additions & 0 deletions azurerm/helpers/azure/cosmos.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package azure

import (
"fmt"

"github.com/Azure/go-autorest/autorest"
)

// it seems the cosmos API is not returning any sort of valid ID in the main response body
// so lets grab it from the response.request.url.path
func CosmosGetIDFromResponse(resp autorest.Response) (string, error) {
if resp.Response == nil {
return "", fmt.Errorf("Error: Unable to get Cosmos ID from Response: http response is nil")
}

if resp.Response.Request == nil {
return "", fmt.Errorf("Error: Unable to get Cosmos ID from Response: Request is nil")
}

if resp.Response.Request.URL == nil {
return "", fmt.Errorf("Error: Unable to get Cosmos ID from Response: URL is nil")
}

return resp.Response.Request.URL.Path, nil
}

type CosmosAccountID struct {
ResourceID
Account string
}

func ParseCosmosAccountID(id string) (*CosmosAccountID, error) {
subid, err := ParseAzureResourceID(id)
if err != nil {
return nil, err
}

account, ok := subid.Path["databaseAccounts"]
if !ok {
return nil, fmt.Errorf("Error: Unable to parse Cosmos Database Resource ID: databaseAccounts is missing from: %s", id)
}

return &CosmosAccountID{
ResourceID: *subid,
Account: account,
}, nil
}

type CosmosDatabaseID struct {
CosmosAccountID
Database string
}

func ParseCosmosDatabaseID(id string) (*CosmosDatabaseID, error) {
subid, err := ParseCosmosAccountID(id)
if err != nil {
return nil, err
}

db, ok := subid.Path["databases"]
if !ok {
return nil, fmt.Errorf("Error: Unable to parse Cosmos Database Resource ID: databases is missing from: %s", id)
}

return &CosmosDatabaseID{
CosmosAccountID: *subid,
Database: db,
}, nil
}

type CosmosDatabaseCollectionID struct {
CosmosDatabaseID
Collection string
}

type CosmosDatabaseContainerID struct {
CosmosDatabaseID
Container string
}

type CosmosKeyspaceID struct {
CosmosAccountID
Keyspace string
}

func ParseCosmosKeyspaceID(id string) (*CosmosKeyspaceID, error) {
subid, err := ParseCosmosAccountID(id)
if err != nil {
return nil, err
}

ks, ok := subid.Path["keyspaces"]
if !ok {
return nil, fmt.Errorf("Error: Unable to parse Cosmos Keyspace Resource ID: keyspaces is missing from: %s", id)
}

return &CosmosKeyspaceID{
CosmosAccountID: *subid,
Keyspace: ks,
}, nil
}

type CosmosKeyspaceTableID struct {
CosmosKeyspaceID
Table string
}

type CosmosTableID struct {
CosmosAccountID
Table string
}

func ParseCosmosTableID(id string) (*CosmosTableID, error) {
subid, err := ParseCosmosAccountID(id)
if err != nil {
return nil, err
}

table, ok := subid.Path["tables"]
if !ok {
return nil, fmt.Errorf("Error: Unable to parse Cosmos Table Resource ID: tables is missing from: %s", id)
}

return &CosmosTableID{
CosmosAccountID: *subid,
Table: table,
}, nil
}
28 changes: 28 additions & 0 deletions azurerm/helpers/validate/cosmos.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package validate

import (
"fmt"
"regexp"
)

func CosmosAccountName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)

// Portal: The value must contain only alphanumeric characters or the following: -
if matched := regexp.MustCompile("^[-a-z0-9]{3,50}$").Match([]byte(value)); !matched {
errors = append(errors, fmt.Errorf("%s name must be 3 - 50 characters long, contain only letters, numbers and hyphens.", k))
}

return warnings, errors
}

func CosmosEntityName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)

if len(value) < 1 || len(value) > 255 {
errors = append(errors, fmt.Errorf(
"%q must be between 1 and 255 characters: %q", k, value))
}

return warnings, errors
}
8 changes: 6 additions & 2 deletions azurerm/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ func Provider() terraform.ResourceProvider {
"azurerm_cdn_profile": dataSourceArmCdnProfile(),
"azurerm_client_config": dataSourceArmClientConfig(),
"azurerm_container_registry": dataSourceArmContainerRegistry(),
"azurerm_cosmosdb_account": dataSourceArmCosmosDBAccount(),
"azurerm_cosmosdb_account": dataSourceArmCosmosDbAccount(),
"azurerm_data_lake_store": dataSourceArmDataLakeStoreAccount(),
"azurerm_dev_test_lab": dataSourceArmDevTestLab(),
"azurerm_dns_zone": dataSourceArmDnsZone(),
Expand Down Expand Up @@ -233,7 +233,11 @@ func Provider() terraform.ResourceProvider {
"azurerm_container_group": resourceArmContainerGroup(),
"azurerm_container_registry": resourceArmContainerRegistry(),
"azurerm_container_service": resourceArmContainerService(),
"azurerm_cosmosdb_account": resourceArmCosmosDBAccount(),
katbyte marked this conversation as resolved.
Show resolved Hide resolved
"azurerm_cosmosdb_account": resourceArmCosmosDbAccount(),
"azurerm_cosmosdb_cassandra_keyspace": resourceArmCosmosDbCassandraKeyspace(),
"azurerm_cosmosdb_mongo_database": resourceArmCosmosDbMongoDatabase(),
"azurerm_cosmosdb_sql_database": resourceArmCosmosDbSQLDatabase(),
"azurerm_cosmosdb_table": resourceArmCosmosDbTable(),
"azurerm_data_factory": resourceArmDataFactory(),
"azurerm_data_factory_dataset_mysql": resourceArmDataFactoryDatasetMySQL(),
"azurerm_data_factory_dataset_postgresql": resourceArmDataFactoryDatasetPostgreSQL(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ import (
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmCosmosDBAccount() *schema.Resource {
func resourceArmCosmosDbAccount() *schema.Resource {
return &schema.Resource{
Create: resourceArmCosmosDBAccountCreate,
Read: resourceArmCosmosDBAccountRead,
Update: resourceArmCosmosDBAccountUpdate,
Delete: resourceArmCosmosDBAccountDelete,
Create: resourceArmCosmosDbAccountCreate,
Read: resourceArmCosmosDbAccountRead,
Update: resourceArmCosmosDbAccountUpdate,
Delete: resourceArmCosmosDbAccountDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Expand Down Expand Up @@ -296,8 +296,8 @@ func resourceArmCosmosDBAccount() *schema.Resource {
}
}

func resourceArmCosmosDBAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosDBClient
func resourceArmCosmosDbAccountCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosAccountsClient
ctx := meta.(*ArmClient).StopContext
log.Printf("[INFO] preparing arguments for AzureRM Cosmos DB Account creation.")

Expand Down Expand Up @@ -368,7 +368,7 @@ func resourceArmCosmosDBAccountCreate(d *schema.ResourceData, meta interface{})
Tags: expandTags(tags),
}

resp, err := resourceArmCosmosDBAccountApiUpsert(client, ctx, resourceGroup, name, account)
resp, err := resourceArmCosmosDbAccountApiUpsert(client, ctx, resourceGroup, name, account)
if err != nil {
return fmt.Errorf("Error creating CosmosDB Account %q (Resource Group %q): %+v", name, resourceGroup, err)
}
Expand All @@ -395,11 +395,11 @@ func resourceArmCosmosDBAccountCreate(d *schema.ResourceData, meta interface{})

d.SetId(*id)

return resourceArmCosmosDBAccountRead(d, meta)
return resourceArmCosmosDbAccountRead(d, meta)
}

func resourceArmCosmosDBAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosDBClient
func resourceArmCosmosDbAccountUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosAccountsClient
ctx := meta.(*ArmClient).StopContext
log.Printf("[INFO] preparing arguments for AzureRM Cosmos DB Account update.")

Expand Down Expand Up @@ -472,7 +472,7 @@ func resourceArmCosmosDBAccountUpdate(d *schema.ResourceData, meta interface{})
Tags: expandTags(tags),
}

if _, err = resourceArmCosmosDBAccountApiUpsert(client, ctx, resourceGroup, name, account); err != nil {
if _, err = resourceArmCosmosDbAccountApiUpsert(client, ctx, resourceGroup, name, account); err != nil {
return fmt.Errorf("Error updating CosmosDB Account %q properties (Resource Group %q): %+v", name, resourceGroup, err)
}

Expand All @@ -488,7 +488,7 @@ func resourceArmCosmosDBAccountUpdate(d *schema.ResourceData, meta interface{})
removedOne = true
continue
}
if *l.ID == "" && *ol.ID == resourceArmCosmosDBAccountGenerateDefaultId(name, *l.LocationName) {
if *l.ID == "" && *ol.ID == resourceArmCosmosDbAccountGenerateDefaultId(name, *l.LocationName) {
continue
}
if *l.ID != *ol.ID {
Expand All @@ -509,14 +509,14 @@ func resourceArmCosmosDBAccountUpdate(d *schema.ResourceData, meta interface{})
}

account.DatabaseAccountCreateUpdateProperties.Locations = &locationsUnchanged
if _, err = resourceArmCosmosDBAccountApiUpsert(client, ctx, resourceGroup, name, account); err != nil {
if _, err = resourceArmCosmosDbAccountApiUpsert(client, ctx, resourceGroup, name, account); err != nil {
return fmt.Errorf("Error removing CosmosDB Account %q renamed locations (Resource Group %q): %+v", name, resourceGroup, err)
}
}

//add any new/renamed locations
account.DatabaseAccountCreateUpdateProperties.Locations = &newLocations
upsertResponse, err := resourceArmCosmosDBAccountApiUpsert(client, ctx, resourceGroup, name, account)
upsertResponse, err := resourceArmCosmosDbAccountApiUpsert(client, ctx, resourceGroup, name, account)
if err != nil {
return fmt.Errorf("Error updating CosmosDB Account %q locations (Resource Group %q): %+v", name, resourceGroup, err)
}
Expand All @@ -543,11 +543,11 @@ func resourceArmCosmosDBAccountUpdate(d *schema.ResourceData, meta interface{})

d.SetId(*id)

return resourceArmCosmosDBAccountRead(d, meta)
return resourceArmCosmosDbAccountRead(d, meta)
}

func resourceArmCosmosDBAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosDBClient
func resourceArmCosmosDbAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosAccountsClient
ctx := meta.(*ArmClient).StopContext

id, err := parseAzureResourceID(d.Id())
Expand Down Expand Up @@ -682,8 +682,8 @@ func resourceArmCosmosDBAccountRead(d *schema.ResourceData, meta interface{}) er
return nil
}

func resourceArmCosmosDBAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosDBClient
func resourceArmCosmosDbAccountDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ArmClient).cosmosAccountsClient
ctx := meta.(*ArmClient).StopContext

id, err := parseAzureResourceID(d.Id())
Expand Down Expand Up @@ -729,7 +729,7 @@ func resourceArmCosmosDBAccountDelete(d *schema.ResourceData, meta interface{})
return nil
}

func resourceArmCosmosDBAccountApiUpsert(client documentdb.DatabaseAccountsClient, ctx context.Context, resourceGroup string, name string, account documentdb.DatabaseAccountCreateUpdateParameters) (*documentdb.DatabaseAccount, error) {
func resourceArmCosmosDbAccountApiUpsert(client documentdb.DatabaseAccountsClient, ctx context.Context, resourceGroup string, name string, account documentdb.DatabaseAccountCreateUpdateParameters) (*documentdb.DatabaseAccount, error) {
future, err := client.CreateOrUpdate(ctx, resourceGroup, name, account)
if err != nil {
return nil, fmt.Errorf("Error creating/updating CosmosDB Account %q (Resource Group %q): %+v", name, resourceGroup, err)
Expand Down Expand Up @@ -791,7 +791,7 @@ func expandAzureRmCosmosDBAccountConsistencyPolicy(d *schema.ResourceData) *docu
return &policy
}

func resourceArmCosmosDBAccountGenerateDefaultId(databaseName string, location string) string {
func resourceArmCosmosDbAccountGenerateDefaultId(databaseName string, location string) string {
return fmt.Sprintf("%s-%s", databaseName, location)
}

Expand All @@ -809,7 +809,7 @@ func expandAzureRmCosmosDBAccountGeoLocations(databaseName string, d *schema.Res
if v, ok := data["prefix"].(string); ok {
data["id"] = v
} else {
data["id"] = utils.String(resourceArmCosmosDBAccountGenerateDefaultId(databaseName, *location.LocationName))
data["id"] = utils.String(resourceArmCosmosDbAccountGenerateDefaultId(databaseName, *location.LocationName))
}
location.ID = utils.String(data["id"].(string))

Expand Down Expand Up @@ -974,7 +974,7 @@ func flattenAzureRmCosmosDBAccountGeoLocations(d *schema.ResourceData, account d
}

//if id is not the default then it must be set via prefix
if id != resourceArmCosmosDBAccountGenerateDefaultId(d.Get("name").(string), lb["location"].(string)) {
if id != resourceArmCosmosDbAccountGenerateDefaultId(d.Get("name").(string), lb["location"].(string)) {
lb["prefix"] = id
}

Expand Down
Loading