Quickstart: Create an Azure Cosmos DB and a container by using an ARM template

APPLIES TO: NoSQL

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 deploying an Azure Resource Manager template (ARM template) to create an Azure Cosmos DB database and a container within that database. You can later store data in this container.

An Azure Resource Manager template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. The template uses declarative syntax. You describe your intended deployment without writing the sequence of programming commands to create the deployment.

If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to Azure button. The template will open in the Azure portal.

Button to deploy the Resource Manager template to Azure.

Prerequisites

An Azure subscription or free Azure Cosmos DB trial account

Review the template

The template used in this quickstart is from Azure Quickstart Templates.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.9.1.41621",
      "templateHash": "13701948159885019128"
    }
  },
  "parameters": {
    "accountName": {
      "type": "string",
      "defaultValue": "[format('sql-{0}', uniqueString(resourceGroup().id))]",
      "metadata": {
        "description": "Azure Cosmos DB account name, max length 44 characters"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for the Azure Cosmos DB account."
      }
    },
    "primaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The primary region for the Azure Cosmos DB account."
      }
    },
    "secondaryRegion": {
      "type": "string",
      "metadata": {
        "description": "The secondary region for the Azure Cosmos DB account."
      }
    },
    "defaultConsistencyLevel": {
      "type": "string",
      "defaultValue": "Session",
      "metadata": {
        "description": "The default consistency level of the Cosmos DB account."
      },
      "allowedValues": [
        "Eventual",
        "ConsistentPrefix",
        "Session",
        "BoundedStaleness",
        "Strong"
      ]
    },
    "maxStalenessPrefix": {
      "type": "int",
      "defaultValue": 100000,
      "metadata": {
        "description": "Max stale requests. Required for BoundedStaleness. Valid ranges, Single Region: 10 to 2147483647. Multi Region: 100000 to 2147483647."
      },
      "maxValue": 2147483647,
      "minValue": 10
    },
    "maxIntervalInSeconds": {
      "type": "int",
      "defaultValue": 300,
      "metadata": {
        "description": "Max lag time (minutes). Required for BoundedStaleness. Valid ranges, Single Region: 5 to 84600. Multi Region: 300 to 86400."
      },
      "maxValue": 86400,
      "minValue": 5
    },
    "systemManagedFailover": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Enable system managed failover for regions"
      },
      "allowedValues": [
        true,
        false
      ]
    },
    "databaseName": {
      "type": "string",
      "defaultValue": "myDatabase",
      "metadata": {
        "description": "The name for the database"
      }
    },
    "containerName": {
      "type": "string",
      "defaultValue": "myContainer",
      "metadata": {
        "description": "The name for the container"
      }
    },
    "throughput": {
      "type": "int",
      "defaultValue": 400,
      "metadata": {
        "description": "The throughput for the container"
      },
      "maxValue": 1000000,
      "minValue": 400
    }
  },
  "variables": {
    "consistencyPolicy": {
      "Eventual": {
        "defaultConsistencyLevel": "Eventual"
      },
      "ConsistentPrefix": {
        "defaultConsistencyLevel": "ConsistentPrefix"
      },
      "Session": {
        "defaultConsistencyLevel": "Session"
      },
      "BoundedStaleness": {
        "defaultConsistencyLevel": "BoundedStaleness",
        "maxStalenessPrefix": "[parameters('maxStalenessPrefix')]",
        "maxIntervalInSeconds": "[parameters('maxIntervalInSeconds')]"
      },
      "Strong": {
        "defaultConsistencyLevel": "Strong"
      }
    },
    "locations": [
      {
        "locationName": "[parameters('primaryRegion')]",
        "failoverPriority": 0,
        "isZoneRedundant": false
      },
      {
        "locationName": "[parameters('secondaryRegion')]",
        "failoverPriority": 1,
        "isZoneRedundant": false
      }
    ]
  },
  "resources": [
    {
      "type": "Microsoft.DocumentDB/databaseAccounts",
      "apiVersion": "2022-05-15",
      "name": "[toLower(parameters('accountName'))]",
      "location": "[parameters('location')]",
      "kind": "GlobalDocumentDB",
      "properties": {
        "consistencyPolicy": "[variables('consistencyPolicy')[parameters('defaultConsistencyLevel')]]",
        "locations": "[variables('locations')]",
        "databaseAccountOfferType": "Standard",
        "enableAutomaticFailover": "[parameters('systemManagedFailover')]"
      }
    },
    {
      "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases",
      "apiVersion": "2022-05-15",
      "name": "[format('{0}/{1}', toLower(parameters('accountName')), parameters('databaseName'))]",
      "properties": {
        "resource": {
          "id": "[parameters('databaseName')]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts', toLower(parameters('accountName')))]"
      ]
    },
    {
      "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers",
      "apiVersion": "2022-05-15",
      "name": "[format('{0}/{1}', format('{0}/{1}', toLower(parameters('accountName')), parameters('databaseName')), parameters('containerName'))]",
      "properties": {
        "resource": {
          "id": "[parameters('containerName')]",
          "partitionKey": {
            "paths": [
              "/myPartitionKey"
            ],
            "kind": "Hash"
          },
          "indexingPolicy": {
            "indexingMode": "consistent",
            "includedPaths": [
              {
                "path": "/*"
              }
            ],
            "excludedPaths": [
              {
                "path": "/myPathToNotIndex/*"
              },
              {
                "path": "/_etag/?"
              }
            ],
            "compositeIndexes": [
              [
                {
                  "path": "/name",
                  "order": "ascending"
                },
                {
                  "path": "/age",
                  "order": "descending"
                }
              ]
            ],
            "spatialIndexes": [
              {
                "path": "/location/*",
                "types": [
                  "Point",
                  "Polygon",
                  "MultiPolygon",
                  "LineString"
                ]
              }
            ]
          },
          "defaultTtl": 86400,
          "uniqueKeyPolicy": {
            "uniqueKeys": [
              {
                "paths": [
                  "/phoneNumber"
                ]
              }
            ]
          }
        },
        "options": {
          "throughput": "[parameters('throughput')]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlDatabases', split(format('{0}/{1}', toLower(parameters('accountName')), parameters('databaseName')), '/')[0], split(format('{0}/{1}', toLower(parameters('accountName')), parameters('databaseName')), '/')[1])]"
      ]
    }
  ]
}

Three Azure resources are defined in the template:

More Azure Cosmos DB template samples can be found in the quickstart template gallery.

Deploy the template

  1. Select the following image to sign in to Azure and open a template. The template creates an Azure Cosmos DB account, a database, and a container.

    Button to deploy the Resource Manager template to Azure.

  2. Select or enter the following values.

    ARM template, Azure Cosmos DB integration, deploy portal

    Unless it is specified, use the default values to create the Azure Cosmos DB resources.

    • Subscription: select an Azure subscription.
    • Resource group: select Create new, enter a unique name for the resource group, and then click OK.
    • Location: select a location. For example, Central US.
    • Account Name: enter a name for the Azure Cosmos DB account. It must be globally unique.
    • Location: enter a location where you want to create your Azure Cosmos DB account. The Azure Cosmos DB account can be in the same location as the resource group.
    • Primary Region: The primary replica region for the Azure Cosmos DB account.
    • Secondary region: The secondary replica region for the Azure Cosmos DB account.
    • Default Consistency Level: The default consistency level for the Azure Cosmos DB account.
    • Max Staleness Prefix: Max stale requests. Required for BoundedStaleness.
    • Max Interval in Seconds: Max lag time. Required for BoundedStaleness.
    • Database Name: The name of the Azure Cosmos DB database.
    • Container Name: The name of the Azure Cosmos DB container.
    • Throughput: The throughput for the container, minimum throughput value is 400 RU/s.
    • I agree to the terms and conditions state above: Select.
  3. Select Purchase. After the Azure Cosmos DB account has been deployed successfully, you get a notification:

    ARM template, Azure Cosmos DB integration, deploy portal notification

The Azure portal is used to deploy the template. In addition to the Azure portal, you can also use the Azure PowerShell, Azure CLI, and REST API. To learn other deployment methods, see Deploy templates.

Validate the deployment

You can either use the Azure portal to check the Azure Cosmos DB account, the database, and the container or use the following Azure CLI or Azure PowerShell script to list the secret created.

echo "Enter your Azure Cosmos DB account name:" &&
read cosmosAccountName &&
echo "Enter the resource group where the Azure Cosmos DB account exists:" &&
read resourcegroupName &&
az cosmosdb show -g $resourcegroupName -n $cosmosAccountName

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, delete the resource group, which deletes the Azure Cosmos DB account and the related resources. To delete the resource group by using Azure CLI or Azure PowerShell:

echo "Enter the Resource Group name:" &&
read resourceGroupName &&
az group delete --name $resourceGroupName &&
echo "Press [ENTER] to continue ..."

Next steps

In this quickstart, you created an Azure Cosmos DB account, a database and a container by using an ARM template and validated the deployment. To learn more about Azure Cosmos DB and Azure Resource Manager, continue on to the articles below.