Warm tip: This article is reproduced from stackoverflow.com, please click
azure-cli bash linux

Storing Output of Azure CLI command as variable

发布于 2020-05-06 08:56:44

I need to store the output of an AZ cli commands that fetches my private IPs as a variable.

I am using the following in a bash script:

echo "Fetching Monitoring Server IP"
SERVER_IP=$(az vm show -n ${THIS_VM_NAME} -g ${RSC_GRP_NAME} --query privateIps -o tsv)
echo "$SERVER_IP

It would appear that this isnt working as when I echo the variable, it comes back empty.

+ THIS_VM_NAME=XXXX-XX-XX-XX-XX
+ echo 'Fetching Monitoring Server IP'
Fetching Monitoring Server IP
++ az vm show -n XXXX-XX-XX-XX-XX3 -g XXXX-XX-XX-XX-XX --query privateIps -o tsv
+ SERVER_IP=
+ echo ''

I will appreciate any pointers on this

Questioner
Samuel Dare
Viewed
33
Charles Xu 2018-11-30 23:46

Edit

The command you post lost a parameter to get the private IPs, you can use the command with the parameter -d or --show-details like this:

az vm show -g resourceGrouName -n vmName -d

But this command just gets all the IPs including the secondary IP.

You can get all the VM primary IPs of each interface through a shell script like this:

count=0
while : ; do
    nic=$(az vm nic list -g resourceGroupName --vm-name vmName --query [$count].id -o tsv)
    if [[ $nic == '' ]]; then
        break
    fi
    privateIps[$count]=$(az vm nic show -g resourceGroupName --vm-name vmName --nic $nic --query ipConfigurations[0].privateIpAddress -o tsv)
    let count++

done
echo ${privateIps[*]}