Tips To Successfully Use AZ CLI With PowerShell

Tips To Successfully Use AZ CLI With PowerShell

Azure CLI is a popular choice among developers to manage Azure resources remotely either via automation scripts or with the help of CI/CD Pipelines.

Azure CLI is not only a Cross-platform command-line interface, but it runs in various command-line tools Windows PowerShell, Cmd, Bash, and other Unix shells.

In complex automation requirements, executing only Azure CLI commands will not give you desired results, most of the time you need to prepare inputs to be passed to these commands and/or capture the output of these commands and process it further until you get desired results. Hence it becomes unavoidable to combine Azure CLI Commands with PowerShell Scripts. (if you don’t want to use the native AZ Module)

The syntax is like that of Bash scripting, so it jells well with Bash script but with PowerShell, you may face some issues while executing Azure CLI Commands. ?So based on our experience, we have come up with QnA which might help you in case you want to start using Azure CLI with your PowerShell scripts.

Below are a few workarounds that we come across but feel free to update the comment box in case you have more.

1.?????I was using Set-AZContext -SubscriptionName $SubscriptionName in OLD Scripts, Should I replace that with the set az account command?

Ans: - In AZ CLI we should not use the set az account command if we deal with multiple subscriptions, instead every CLI accepts subscriptions as input via the --subscription param.

When we use this parameter, we can effectively deal with objects in multiple subscriptions, unlike PowerShell.

No alt text provided for this image

2.?????My PowerShell command was returning output in table format, should I return the output of the CLI command in table format only?

Ans: - PowerShell’s default output is in object format which is displayed in table format on the console.

Az CLI returns output in three formats JSON, Table, and TSV

Even though each of these output formats has its unique uses, for operating AZ CLI In a PowerShell application, always return output in JSON format and then use PowerShell native commands to convert it from JSON into PowerShell Object.

The output returned by AZ CLI in the table or TSV format are not recognized by PowerShell as table or TSV, these are just an array of string to PowerShell hence you cannot make use of the output like a PS Custom Object.


3.?????When Calling AzureRM\AZ Command, I was passing Parameters as

do-someazcommand -inputParam1 $param1

but the same is not working in AZ CLI

Ans: - There are differences in the way PowerShell operates and the way AZ CLI Operates, to make sure the AZ CLI command gets executed every time successfully, take the following measures.

???????????????I.????????Make use of Double Quotes, always enclose your inputs in double quotes irrespective of whether your input has space or not.

If a parameter's value begins with a hyphen or contains a pipe (‘ | ‘) character, Azure CLI tries to parse it as a parameter name. To parse it as a value, use = to concatenate the parameter name and value: --password="-VerySecret".

No alt text provided for this image
No alt text provided for this image

??????????????II.???????To Pass an empty string or null value as input send it as '""'

????????????III.????????There are special characters of PowerShell, such as at @. To run Azure CLI in PowerShell, add ` before the special character to escape it. You can also enclose the value in single or double quotes "/".

No alt text provided for this image

4.?????I am Executing Parallel PowerShell Jobs but most of the jobs fail due to some Azure Login Issues, even though I am using the common module to log in to Azure, still AZ CLI fails with an error that cannot access resources. Or Similar Issues Related to login, how to fix them.

No alt text provided for this image
No alt text provided for this image

Ans: - If multiple jobs are running in parallel, they might be attempting to log in to Azure using the same credentials on same host simultaneously. This can sometimes lead to conflicts and intermittent login failures.

To mitigate this, you can use a semaphore or some other form of synchronization to ensure that only one script block attempts to log in at a time.

Method 1.

To ensure that only one script block attempts to log in at a time, you can use a PowerShell mutex (mutual exclusion) to create a semaphore. A mutex is a synchronization primitive that allows only one thread or process to access a shared resource at a time. In this case, we'll use it to ensure that only one script block can log in to Azure at any given time.

Here's how you can use a mutex in PowerShell to synchronize the login process:

No alt text provided for this image

Method 2:

When we execute Az CLI Command, It saves context information in below two files

???????????~/.azure/azureProfile.json & ~/.azure/accessTokens.json

These are the common locations shared across all the jobs and scripts getting executed under one login ID, that’s why when we run multiple threads there are chances that multiple sessions try to read and write the same file and this causes conflict.

Also, when you use commands like az account clear or az account set --subscription, it overwrites these files causing other threads, and scripts to lose access on the Azure subscription.

To avoid potential failures, you may isolate the Azure CLI configuration folder for each script by setting the environment variable AZURE_CONFIG_DIR for each script to a separate directory. Azure CLI commands in that script save the configuration and token cache to the configured location instead of the default ~/.azure folder.

So before you import common module or login to azure in your script block, always create separate space for your thread specific azure Profile and access Token files as below.

No alt text provided for this image

If you use this method, make sure while adding extensions, the user –system switch. This will add an extension so the system directory and extension will be available to all threads.

No alt text provided for this image

5.?????I am working with a resource that is not supported by az cli command, should I use PowerShell instead?

Ans: - A service you want to work with may not have Azure CLI support. You can use the az resource commands to work with these resources.

If generic update parameters and az resource don't meet your needs, you can use the az rest command to call the REST API. The command automatically authenticates using the logged-in credential and sets header Content-Type: application/json. For more information, see Azure REST API reference.

No alt text provided for this image

6.?????How to handle errors in CLI.

Ans: - By default, Azure CLI doesn't create exceptions for PowerShell to catch. An alternative is to use the $? automatic variable. This variable contains the status of the most recent command. If the previous command fails, $? has the value of $False.

No alt text provided for this image

Another Way to redirect STDError to null in combination with $ErrorActionPreference

No alt text provided for this image

If any CLI Commands are throwing warnings, then you can suppress the warning with a switch --only-show-error

?

7.?????I was setting up storage context to connect to azure storage account in AzureRM Command but there is no such command available in AZ CLI.

Ans: - to connect to a storage account using AZ CLI there Is no need to setup storage context, for performing any storage-related operations you first need to generate SAS token for required services and permissions and then use this SAS token with AZ CLI commands or AZ Copy command.

If you are not able to perform operations using the SAS token then double-check that your storage account URL is not ending with “\” or “\ /” or “/ /“operator, for fix this we need to replace “\” with “/”.

Thank you for your time going through this article, hopefully, some of the points mentioned here have helped you to go get unblocked with Azure CLI issues.

Contributions to This Article: Vishwajeet Sawant Anurag Sunil Vidya Nikam

Do let me know your feedback and suggestions.

Contents, Some of the Images and Code Snippets For this Article Are Taken From below sites, you can refer to these articles to dive deeper:

·??????Tips for using the Azure CLI successfully

·??????about_Quoting_Rules

·??????Choose the right Azure command-line tool

·??????Microsoft Graph REST API v1.0 endpoint reference

·??????Azure REST API reference

·??????Configure the Azure CLI

·??????Learn to use Bash with Azure CLI

·??????Query Azure CLI command output

·??????Use variables in Azure CLI commands

·??????Find Azure CLI samples

?

?

?

???????????

?

要查看或添加评论,请登录

社区洞察

其他会员也浏览了