Check whether a Cosmos DB exists using PowerShell

Viewed 38

I am trying to check whether a Cosmos DB exists or not using Powershell in Octopus. If Not I need to create it. Thats the requirement

$ApplicationShortName = "stc"
$resourceGroup = $OctopusParameters["AzurePlatform.Application[$ApplicationShortName].ResourceGroup.Name"]
$CosmosAccount = $OctopusParameters["AzurePlatform.Application[$ApplicationShortName].CosmosDbAccount.Name"]
$databaseName='sdsd'
Write-Host "Resource Group : $resourceGroup"
Write-host "Cosmos Account : $CosmosAccount"


#Check whether database exists
Get-AzCosmosDBSqlDatabase -ResourceGroupName $resourceGroup -AccountName $CosmosAccount -Name $databaseName

But here the problem is if DB actually exists, the above function works fine. But if DB not exists, it simply triggers an error.

So how to check whether the DB exists or not. So if not exists I need to fire this command

New-AzCosmosDBSqlDatabase -AccountName $CosmosAccount -Name $databaseName -ResourceGroupName $resourceGroup
1 Answers

You should be able to handle this process within your Octopus script - take a look at the documentation for error handling for Octopus scripts

The best practice here is to always check the exit code when invoking programs:

& ping 255.255.255.0
if ($LastExitCode -ne 0) {
    throw "Couldn't find 255.255.255.0"
}

By checking the $LastExitCode, you can determine whether there was a success in your step and drive your database creation.

Also worth noting that if you use the az cli instead of the PowerShell commands, there's a specific command for what you're doing here that returns a boolean! Check out az cosmosdb database exists if you want to try and get it that way without having to manually check exit codes.

Related