Obtain primary, secondary, read, or read-write keys in Azure Cosmos DB
Article
APPLIES TO:
NoSQL
MongoDB
Cassandra
Gremlin
Table
Primary/secondary keys provide access to all the administrative resources for the database account. Primary/secondary keys:
Provide access to accounts, databases, users, and permissions.
Can't be used to provide granular access to containers and documents.
Are created during the creation of an account.
Can be regenerated at any time.
Warning
Microsoft recommends that you use the most secure authentication flow available. The authentication flow described in this procedure requires a very high degree of trust in the application, and carries risks that are not present in other flows. You should only use this flow when other more secure flows, such as managed identities, aren't viable.
For Azure Cosmos DB, Microsoft Entra authentication is the most secure authentication mechanism available. Review the appropriate security guide for your API:
Each account consists of two keys: a primary key and a secondary key. The purpose of dual keys is so that you can regenerate, or roll, keys, providing continuous access to your account and data.
Primary/secondary keys come in two versions: read-write and read-only. The read-only keys only allow read operations on the account. They don't provide access to read permissions resources.
Prerequisites
An existing Azure Cosmos DB account
Get your primary key
The primary key can usually be located using the Azure portal or through automation.
This example Bicep template outputs all credentials for an existing Azure Cosmos DB account.
metadata description = 'Gets all keys and connection strings for an Azure Cosmos DB account.'
@description('The name of the Azure Cosmos DB account.')
param accountName string
resource account 'Microsoft.DocumentDB/databaseAccounts@2024-05-15' existing = {
name: accountName
}
output endpoint string = account.properties.documentEndpoint
var keys = account.listKeys()
output keys object = {
primary: {
readWrite: keys.primaryMasterKey
readOnly: keys.primaryReadonlyMasterKey
}
secondary: {
readWrite: keys.secondaryMasterKey
readOnly: keys.secondaryReadonlyMasterKey
}
}
var connectionStrings = account.listConnectionStrings()
output connectionStrings object = {
primary: {
readWrite: connectionStrings.connectionStrings[0].connectionString
readOnly: connectionStrings.connectionStrings[1].connectionString
}
secondary: {
readWrite: connectionStrings.connectionStrings[2].connectionString
readOnly: connectionStrings.connectionStrings[3].connectionString
}
}
Warning
This Bicep template will trigger a linter warning for Bicep. Ideally, production Bicep templates should not output secrets. This sample intentionally does not supress this linter warning. For more information, see linter rule - outputs should not contain secrets.