แก้ไข

แชร์ผ่าน


Quickstart - Create an Azure Cosmos DB database and container using Terraform

Azure Cosmos DB is Microsoft’s fast NoSQL database with open APIs for any scale. You can use Azure Cosmos DB to quickly create and query key/value databases, document databases, and graph databases. Without a credit card or an Azure subscription, you can set up a free Try Azure Cosmos DB account. This quickstart focuses on the process of deployments via Terraform to create an Azure Cosmos database and a container within that database. You can later store data in this container.

Prerequisites

An Azure subscription or free Azure Cosmos DB trial account

  • If you don't have an Azure account, create a free account before you begin.

Terraform should be installed on your local computer. Installation instructions can be found here.

Review the Terraform File

The Terraform files used in this quickstart can be found on the terraform samples repository. Create the below three files: providers.tf, main.tf and variables.tf. Variables can be set in command line or alternatively with a terraforms.tfvars file.

Key Terraform parameters

The following table summarizes the critical variables used in this quickstart, their scope, constraints, and example values.

Parameter Scope Description and constraints Example value
prefix Naming Prefix used for all resource names. Must be lowercase, alphanumeric, and unique per subscription. cosmosdemo
location Resource group Azure region for the resource group. This location applies to the resource group only, not the Cosmos DB account. eastus
cosmosdb_account_location Cosmos DB account Azure region for the Azure Cosmos DB account. This can differ from the resource group location. eastus
throughput Database (RU/s) Provisioned throughput for the SQL database in request units per second (RU/s). Must be between 400 and 1,000,000 RU/s. 400

Provider Terraform File

terraform {
  required_version = ">= 1.0"

  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = ">= 3.0, < 4.0"
    }
    random = {
      source  = "hashicorp/random"
      version = ">= 3.0"
    }
  }
}

provider "azurerm" {
  features {
    resource_group {
      prevent_deletion_if_contains_resources = false
    }
  }
}

Main Terraform File

resource "azurerm_resource_group" "example" {
  name     = "${random_pet.prefix.id}-rg"
  location = var.location
}

resource "azurerm_cosmosdb_account" "example" {
  name                      = "${random_pet.prefix.id}-cosmosdb"
  location                  = var.cosmosdb_account_location
  resource_group_name       = azurerm_resource_group.example.name
  offer_type                = "Standard"
  kind                      = "GlobalDocumentDB"
  enable_automatic_failover = false
  geo_location {
    location          = var.location
    failover_priority = 0
  }
  consistency_policy {
    consistency_level       = "BoundedStaleness"
    max_interval_in_seconds = 300
    max_staleness_prefix    = 100000
  }
  depends_on = [
    azurerm_resource_group.example
  ]
}

resource "azurerm_cosmosdb_sql_database" "main" {
  name                = "${random_pet.prefix.id}-sqldb"
  resource_group_name = azurerm_resource_group.example.name
  account_name        = azurerm_cosmosdb_account.example.name
  throughput          = var.throughput
}

resource "azurerm_cosmosdb_sql_container" "example" {
  name                  = "${random_pet.prefix.id}-sql-container"
  resource_group_name   = azurerm_resource_group.example.name
  account_name          = azurerm_cosmosdb_account.example.name
  database_name         = azurerm_cosmosdb_sql_database.main.name
  partition_key_path    = "/definition/id"
  partition_key_version = 1
  throughput            = var.throughput

  indexing_policy {
    indexing_mode = "consistent"

    included_path {
      path = "/*"
    }

    included_path {
      path = "/included/?"
    }

    excluded_path {
      path = "/excluded/?"
    }
  }

  unique_key {
    paths = ["/definition/idlong", "/definition/idshort"]
  }
}

resource "random_pet" "prefix" {
  prefix = var.prefix
  length = 1
}

Three Cosmos DB resources are defined in the main terraform file.

Variables Terraform File

variable "prefix" {
  type        = string
  default     = "cosmosdb-manualscale"
  description = "Prefix of the resource name"
}

variable "location" {
  type        = string
  default     = "Canada Central"
  description = "Resource group location"
}

variable "cosmosdb_account_location" {
  type        = string
  default     = "Canada Central"
  description = "Cosmos db account location"
}

variable "throughput" {
  type        = number
  default     = 400
  description = "Cosmos db database throughput"
  validation {
    condition     = var.throughput >= 400 && var.throughput <= 1000000
    error_message = "Cosmos db manual throughput should be equal to or greater than 400 and less than or equal to 1000000."
  }
  validation {
    condition     = var.throughput % 100 == 0
    error_message = "Cosmos db throughput should be in increments of 100."
  }
}

Deploy via terraform

  1. Save the terraform files as main.tf, variables.tf and providers.tf to your local computer.
  2. Sign in to your terminal via Azure CLI or PowerShell
  3. Deploy via Terraform commands
    • terraform init
      Expected result: Terraform initializes successfully and downloads the azurerm provider.
    • terraform plan
      Expected result: The plan output shows 3 to add, 0 to change, 0 to destroy.
    • terraform apply
      Expected result: The final output includes Apply complete! Resources: 3 added, 0 changed, 0 destroyed.

Validate the deployment

Use the Azure portal, Azure CLI, or Azure PowerShell to list the deployed resources in the resource group.

az resource list --resource-group "your resource group name"

Expected result: The output lists a Microsoft.DocumentDB/databaseAccounts resource along with its database and container.

Clean up resources

If you plan to continue working with subsequent quickstarts and tutorials, you might want to leave these resources in place. When no longer needed, use the Azure portal, Azure CLI, or Azure PowerShell to delete the resource group and its resources.

az group delete --name "your resource group name"

Expected result: Azure CLI confirms the resource group deletion and no longer lists it in the subscription.

Next steps

In this quickstart, you created an Azure Cosmos account, a database and a container via terraform and validated the deployment. To learn more about Azure Cosmos DB and Terraform, continue on to the articles below.