'Azure CLI Exception Handling
I have installed the azure cli on my local system and I am able to run the azure cli commands in Windows Powershell. When I run any command which is not correct or throwing any exception, I am able to see it on the console. But how can I capture this exception using Try...Catch . I want to handle the exception using try..catch in powershell script.
Please help me on this.
code snippet:
Suppose my ClientSecret is wrong then the below command will through an exception, how can I capture this in Catch block??
Try
{
$TenantId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$ClientId = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
$ClientSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
az login --service-principal -u $ClientId -p $ClientSecret --tenant $TenantId
}
Catch
{
$ErrorMessage = $_.Exception.Message
Write-Output $ErrorMessage
}
Solution 1:[1]
More recent versions of the CLI support a global parameter --only-show-errors
which will suppress preview messages. So you could amend the Avshalom answer like this to solve the issue UNeverNo raised:
if (az login --service-principal -u $ClientId -p $ClientSecret --tenant $TenantId --only-show-errors)
{
"Success"
}
else {"Error"}
Solution 2:[2]
Answering that late to help others facing the same issue. Try to store the output in a parameter and check if it is null or not. As azure commands give the output in json format, we can use:
$output = az login -u "username" -p "password" | ConvertFrom-Json
if (!$output) {
Write-Error "Error validating the credentials"
return
}
Solution 3:[3]
In regular Powershell commands you can use the CommonParameter -ErrorAction Stop
But for the AzureCli az command i think you can use a simple if statement:
if (az login --service-principal -u $ClientId -p $ClientSecret --tenant $TenantId)
{
"Success"
}
else {"Error"}
Or check the last exit state using the $?
Automatic variable after the login attempt:
if (!$?) {"Error"}
Solution 4:[4]
Try using the --query
operator to check for things you need. For example, Avshalom's answer might be correct if you query for state enabled or something. I am doing similar things in some places:
# Create the Web App if it does not already exist
if(-Not (az webapp show --name $webAppName --resource-group $resourceGroupName))
{
az webapp create --name $webAppName --resource-group $resourceGroupName --plan $servicePlanName --tags 'displayName=WebApp'
}
Solution 5:[5]
I had a requirement to check if a particular Apim Api Version Set exists or not, for which there are no standard "exists" commands available. Below is how I managed to get the result.
$result = az apim api versionset list --resource-group MyResourceGroup --service-name MyApim --query "[?name=='MyVersionSet']" | ConvertFrom-Json
$exists = $result.Length -gt 0
$exists
will return true if the version set exists.
Solution 6:[6]
So I could capture the correct error from Az Cli, and to avoid having to add an extra line for each az command, I created my own az-ps
function to wrap all az calls:
function az-ps {
$result = az $args 2>&1
if(!$?) { Write-Error -Message "az $args returned error $result" -ErrorAction Stop }
return $result
}
Then I just called this instead of az
- e.g.:
$databases = az-ps sql midb list --resource-group myResourceGroup --managed-instance myManagedSqlInstance
If this returns an error you get:
Write-Error: az_error_test.ps1:11
Line |
11 | … databases = az-ps sql midb list --resource-group myResourceGroup --manage …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| az sql midb list --resource-group myResourceGroup --managed-instance
| myManagedSqlInstance returned error ERROR: (ParentResourceNotFound) Can not perform requested operation
| on nested resource. Parent resource 'myManagedSqlInstance' not found. Code: ParentResourceNotFound
| Message: Can not perform requested operation on nested resource. Parent resource 'myManagedSqlInstance'
| not found.
What this does:
It passes all the $args
to az
so it should accept any args that az does
The 2>&1
param means that the Error output (2) will get redirected to the normal output (1) - so $result
will contain the output of the az
call if it is successful, or the error message if it fails.
$?
is a special powershell var the contains true
if the last command succeeded of false
if it fails
-ErrorAction Stop
will prevent the powershell script from continuing (unless there is a try/catch block)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Josh |
Solution 2 | |
Solution 3 | |
Solution 4 | Victorio Berra |
Solution 5 | Rajkumar Damodaran |
Solution 6 |