Connection string and account key operations for an Azure Cosmos DB account using PowerShell
APPLIES TO:
SQL API
Cassandra API
Gremlin API
Table API
Azure Cosmos DB API for MongoDB
Note
This article uses the Azure Az PowerShell module, which is the recommended PowerShell module for interacting with Azure. To get started with the Az PowerShell module, see Install Azure PowerShell. To learn how to migrate to the Az PowerShell module, see Migrate Azure PowerShell from AzureRM to Az.
This sample requires Azure PowerShell Az 5.4.0 or later. Run Get-Module -ListAvailable Az to see which versions are installed.
If you need to install, see Install Azure PowerShell module.
Run Connect-AzAccount to sign in to Azure.
Sample script
Note
This sample demonstrates using a SQL API account. To use this sample for other APIs, copy the related properties and apply to your API-specific script
# Reference: Az.CosmosDB | https://docs.microsoft.com/powershell/module/az.cosmosdb
# --------------------------------------------------
# Purpose
# List an account's connection strings and keys; regenerate a key.
# --------------------------------------------------
# Variables - ***** SUBSTITUTE YOUR VALUES *****
$resourceGroupName = "myResourceGroup" # Resource Group must already exist
$accountName = "myaccount" # Must be all lower case
$keyKind = "primary" # Other key kinds: secondary, primaryReadOnly, secondaryReadOnly
# --------------------------------------------------
Write-Host "List connection strings"
Get-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName `
-Name $accountName -Type "ConnectionStrings"
Write-Host "List keys"
Get-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName `
-Name $accountName -Type "Keys"
Write-Host "Reset key"
New-AzCosmosDBAccountKey -ResourceGroupName $resourceGroupName `
-Name $accountName -KeyKind $keyKind
Clean up deployment
After the script sample has been run, the following command can be used to remove the resource group and all resources associated with it.
Remove-AzResourceGroup -ResourceGroupName "myResourceGroup"
Script explanation
This script uses the following commands. Each command in the table links to command specific documentation.
| Command | Notes |
|---|---|
| Azure Cosmos DB | |
| Get-AzCosmosDBAccountKey | Gets the connection string or key (read-write or read-only) for a Cosmos DB Account. |
| New-AzCosmosDBAccountKey | Regenerate the specified key for a Cosmos DB Account. |
| Azure Resource Groups | |
| Remove-AzResourceGroup | Deletes a resource group including all nested resources. |
Next steps
For more information on the Azure PowerShell, see Azure PowerShell documentation.