如何在 Bash 環境中使用 Azure CLI

Azure CLI 參考命令可以在數個不同的 殼層環境中執行,但 Microsoft Docs 主要使用 Bash 環境。 如果您不熟悉 Bash 和 Azure CLI,本文是開始學習旅程的絕佳位置。 請輕鬆完成本文,就像教學課程一樣,瞭解如何在Bash環境中使用 Azure CLI。

在本文中,您將學會如何:

  • 以 JSON 字典或陣列形式查詢結果
  • 將輸出格式化為 JSON、資料表或 TSV
  • 查詢、篩選和格式化單一和多個值
  • 使用 if/exists/then 和 case 語法
  • 用於迴圈
  • 使用 grep、sed、paste 和 bc 命令
  • 填入和使用殼層和環境變數

如果您沒有 Azure 訂用帳戶,請在開始之前建立 Azure 免費帳戶

啟動Bash

使用 Azure Cloud ShellAzure CLI 的本機安裝來啟動 Bash。 本文假設您是在 Docker 容器中使用 Azure Cloud Shell 或在本機執行 Azure CLI 來執行 Bash。

查詢字典結果

一律只傳回單一物件的命令會傳回 JSON 字典。 字典是使用索引鍵存取的未排序物件。 在本文中,我們將從使用 Account Show 命令查詢 Account 對象開始。

az account show
az account show --output json # JSON is the default format

下列 JSON 字典輸出有一些為了簡潔而省略的欄位,並已移除或泛型識別資訊。

bash-5.1# az account show
{
  "environmentName": "AzureCloud",
  "isDefault": true,
  "managedByTenants": [],
  "name": "My test subscription",
  "state": "Enabled",
  "user": {
    "name": "user@contoso.com",
    "type": "user"
  }
}

將輸出格式化為 YAML

--output yaml使用 自變數 (或-o yaml) 以 yaml 格式格式化輸出,這是純文字資料串行化格式。 YAML 通常比 JSON 更容易讀取,而且很容易對應到該格式。 某些應用程式和 CLI 命令會採用 YAML 作為組態輸入,而不是 JSON。

az account show --output yaml

如需將輸出格式化為 yaml 的詳細資訊,請參閱 YAML 輸出格式

將輸出格式化為數據表

--output table使用 自變數 (或-o table) 將輸出格式化為 ASCII 資料表。 巢狀物件不會包含在數據表輸出中,但仍可篩選為查詢的一部分。

az account show --output table

如需將輸出格式化為數據表的詳細資訊,請參閱 表格輸出格式

查詢和格式化單一值和巢狀值

下列查詢示範查詢單一值,包括 JSON 字典輸出中的巢狀值。 此集合中的最後一個查詢示範如何使用 -o tsv 自變數來格式化輸出。 這個自變數會以製表符和換行符分隔值的形式傳回結果。 此動作適用於移除所傳回值中的引號,這對於將輸出取用到需要以某種形式處理文字的其他命令和工具很有用(如本文稍後所示)。

az account show --query name # Querying a single value
az account show --query name -o tsv # Removes quotation marks from the output

az account show --query user.name # Querying a nested value
az account show --query user.name -o tsv # Removes quotation marks from the output

從數位查詢和格式化屬性

下列查詢示範如何在 JSON 陣列中取得屬性。 取得訂用帳戶屬性,顯示為訂用帳戶的數據表。

az account list --query "[].{subscription_id:id, name:name, isDefault:isDefault}" -o table

此查詢會傳回類似下列的結果:

Subscription_id                       Name                                               IsDefault
------------------------------------  -------------------------------------------------  -----------
11111111-3ddc-45ce-8334-c7b28a9e1c3a  C & L Azure developer experience content projects  False
22222222-8f1c-409b-af1e-8e2e65d9b90a  DevCenter - Infrastructure - Dogfood               False
33333333-c080-42a7-8973-1aa853ab4df3  Babel                                              False

查詢和格式化多個值,包括巢狀值

若要取得多個屬性,請將表達式放在方括弧 [ ] (多重選取清單) 中,做為逗號分隔清單。 下列查詢示範使用多個輸出格式查詢 JSON 字典輸出中的多個值。

az account show --query [name,id,user.name] # return multiple values
az account show --query [name,id,user.name] -o table # return multiple values as a table

如需傳回多個值的詳細資訊,請參閱 取得多個值

在查詢中重新命名屬性

下列查詢示範在查詢多個值時,使用 { } (多重選取哈希) 運算符來取得字典,而不是陣列。 它也示範在查詢結果中重新命名屬性。

az account show --query "{SubscriptionName: name, SubscriptionId: id, UserName: user.name}" # Rename the values returned
az account show --query "{SubscriptionName: name, SubscriptionId: id, UserName: user.name}" -o table # Rename the values returned in a table

如需在查詢中重新命名屬性的詳細資訊,請參閱 在查詢中重新命名屬性。

查詢布爾值

布爾值假設為 true,因此 "[?isDefault]" 命令的 az account list 查詢語法會傳回目前的預設訂用帳戶。 若要取得 false 值,您必須使用逸出字元,例如 \

下列查詢示範查詢訂用帳戶中的所有帳戶,如果指定帳戶有多個訂用帳戶,則可能會傳回 JSON 陣列,然後查詢哪個帳戶是預設訂用帳戶。 它也會示範查詢不是預設訂用帳戶的帳戶。 這些查詢會以您先前學到的內容為基礎來篩選和格式化結果。 最後,最終查詢示範如何將查詢結果儲存在變數中。

az account list
az account list --query "[?isDefault]" # Returns the default subscription
az account list --query "[?isDefault]" -o table # Returns the default subscription as a table
az account list --query "[?isDefault].[name,id]" # Returns the name and id of the default subscription
az account list --query "[?isDefault].[name,id]" -o table # Returns the name and id of the default subscription as a table
az account list --query "[?isDefault].{SubscriptionName: name, SubscriptionId: id}" -o table # Returns the name and id of the default subscription as a table with friendly names

az account list --query "[?isDefault == \`false\`]" # Returns all non-default subscriptions, if any
az account list --query "[?isDefault == \`false\`].name" -o table # Returns all non-default subscriptions, if any, as a table

az account list --query "[?isDefault].id" -o tsv # Returns the subscription id without quotation marks
subscriptionId="$(az account list --query "[?isDefault].id" -o tsv)" # Captures the subscription id as a variable.
echo $subscriptionId # Returns the contents of the variable.
az account list --query "[? contains(name, 'Test')].id" -o tsv # Returns the subscription id of a non-default subscription containing the substring 'Test'
subscriptionId="$(az account list --query "[? contains(name, 'Test')].id" -o tsv) # Captures the subscription id as a variable. 
az account set -s $subscriptionId # Sets the current active subscription

使用變數和隨機化建立物件

設定隨機值以用於後續命令

設定及使用隨機值以用於變數,可讓您多次執行腳本,而不會發生命名衝突。 可能會發生命名衝突,因為值在整個服務中必須是唯一的,或因為您刪除的物件仍然存在於 Azure 中,直到刪除程式完成為止。

$RANDOM 是bash函式(不是常數),會傳回隨機帶正負號的16位整數(從0到32767)。 此命令 let 是內建的Bash命令,用來評估算術表達式。 使用下列命令會針對大部分用途建立足夠唯一的值。

let "randomIdentifier=$RANDOM*$RANDOM"

使用空格和引號

空格用於分隔命令、選項和自變數。 使用引號告訴 Bash 殼層忽略所有特殊字元,其中空格符是特殊字元。 當 Bash 殼層看到第一個引號時,它會忽略特殊字元,直到結尾引號為止。 不過,有時候您想要Bash殼層剖析某些特殊字元,例如美元符號、背引號和反斜杠。 在此案例中,請使用雙引號。

下列命令使用 az group create 命令來說明單引號和雙引號的使用。 這些命令可用來處理空格,並在使用變數和建立物件時評估特殊字元。

resourceGroup='msdocs-learn-bash-$randomIdentifier'
echo $resourceGroup # The $ is ignored in the creation of the $resourceGroup variable
resourceGroup="msdocs-learn-bash-$randomIdentifier"
echo $resourceGroup # The $randomIdentifier is evaluated when defining the $resourceGroup variable
location="East US" # The space is ignored when defining the $location variable
echo The value of the location variable is $location # The value of the $location variable is evaluated
echo "The value of the location variable is $location" # The value of the $location variable is evaluated
echo "The value of the location variable is \$location" # The value of the $location variable is not evaluated
echo 'The value of the location variable is $location' # The value of the $location variable is not evaluated
az group create --name $resourceGroup --location $location # Notice that the space in the $location variable is not ignored and the command fails as it treats the value after the space as a new command 
az group create --name $resourceGroup --location "$location" # Notice that the space in the $location variable is ignored and the location argument accepts the entire string as the value 

在 JSON 字典輸出中,檢閱已建立之資源群組的屬性。

使用 If Then Else 判斷變數是否為 Null

若要評估字串,請使用 != 和 來評估數位使用 -ne。 下列 If Then Else 語句會評估是否已設定$resourceGroup變數。 如果是,則會傳回變數的值。 如果沒有,它會設定變數。

if [ $resourceGroup != '' ]; then
   echo $resourceGroup
else
   resourceGroup="msdocs-learn-bash-$randomIdentifier"
fi

使用 If Then 建立或刪除資源群組

只有當具有指定名稱的一個資源群組不存在時,下列腳本才會建立新的資源群組。

if [ $(az group exists --name $resourceGroup) = false ]; then 
   az group create --name $resourceGroup --location "$location" 
else
   echo $resourceGroup
fi

如果已有指定名稱的現有資源群組,下列腳本會刪除現有的資源群組。 您可以使用 --no-wait 自變數傳回控件,而不需要等待命令完成。 不過,在本文中,我們想要等候資源群組刪除再繼續。 如需異步操作的詳細資訊,請參閱 異步操作。 我們會示範本文結尾的 --no-wait 自變數用法。

if [ $(az group exists --name $resourceGroup) = true ]; then 
   az group delete --name $resourceGroup -y # --no-wait
else
   echo The $resourceGroup resource group does not exist
fi

使用 Grep 判斷資源群組是否存在,如果資源群組不存在,請建立資源群組

下列命令會將命令的 az group list 輸出管線傳送至 grep 命令。 如果指定的資源群組不存在,命令會使用先前定義的變數來建立資源群組。

az group list --output tsv | grep $resourceGroup -q || az group create --name $resourceGroup --location "$location"

使用CASE語句來判斷資源群組是否存在,如果資源群組不存在,請建立資源群組

只有在具有指定名稱的群組不存在時,下列 CASE 語句才會建立新的資源群組。 如果其中一個具有指定名稱,則 CASE 語句會響應資源群組存在。

var=$(az group list --query "[? contains(name, '$resourceGroup')].name" --output tsv)
case $resourceGroup in
$var)
echo The $resourceGroup resource group already exists.;;
*)
az group create --name $resourceGroup --location "$location";;
esac

使用 for 循環和查詢陣列

在本文的本節中,我們會建立記憶體帳戶,然後使用 for 迴圈來建立 Blob 和容器。 我們也示範查詢 JSON 陣列和使用環境變數。

建立儲存體帳戶

下列命令會 使用 az storage account create 命令來建立我們在建立記憶體容器時使用的記憶體帳戶。

storageAccount="learnbash$randomIdentifier"
az storage account create --name $storageAccount --location "$location" --resource-group $resourceGroup --sku Standard_LRS --encryption-services blob

取得記憶體帳戶金鑰

下列命令會使用 az storage account keys list 命令傳回記憶體帳戶密鑰值。 然後,我們會將索引鍵值儲存在變數中,以在建立記憶體容器時使用。

az storage account keys list --resource-group $resourceGroup --account-name $storageAccount --query "[].value" -o tsv # returns both storage account key values

az storage account keys list --resource-group $resourceGroup --account-name $storageAccount --query "[0].value" -o tsv # returns a single storage account key value

accountKey=$(az storage account keys list --resource-group $resourceGroup --account-name $storageAccount --query "[0].value" -o tsv)

echo $accountKey

建立記憶體容器

首先, 我們會使用 az storage container create 來建立單一記憶體容器,然後使用 az storage container list 來查詢所建立容器的名稱。

container="learningbash"
az storage container create --account-name $storageAccount --account-key $accountKey --name $container

az storage container list --account-name $storageAccount --account-key $accountKey --query [].name

將數據上傳至容器

下列腳本會使用 for 迴圈建立三個範例檔案。

for i in `seq 1 3`; do
    echo $randomIdentifier > container_size_sample_file_$i.txt
done

下列腳本會使用 az storage blob upload-batch 命令,將 Blob 上傳至記憶體容器。

az storage blob upload-batch \
    --pattern "container_size_sample_file_*.txt" \
    --source . \
    --destination $container \
    --account-key $accountKey \
    --account-name $storageAccount

下列腳本會使用 az storage blob list 命令來列出容器中的 Blob。

az storage blob list \
    --container-name $container \
    --account-key $accountKey \
    --account-name $storageAccount \
    --query "[].name"

下列文本會顯示記憶體容器中的位元組總數。

bytes=`az storage blob list \
    --container-name $container \
    --account-key $accountKey \
    --account-name $storageAccount \
    --query "[*].[properties.contentLength]" \
    --output tsv | paste -s -d+ | bc`

echo "Total bytes in container: $bytes"
echo $bytes

使用迴圈建立許多容器

接下來,我們會使用迴圈建立多個容器,示範幾個撰寫迴圈的方式。

for i in `seq 1 4`; do 
az storage container create --account-name $storageAccount --account-key $accountKey --name learnbash-$i
done

for value in {5..8}
for (( i=5; i<10; i++));
do
az storage container create --account-name $storageAccount --account-key $accountKey --name learnbash-$i
done

az storage container list --account-name $storageAccount --account-key $accountKey --query [].name

使用 EXPORT 來定義環境變數

在上述記憶體容器文本中,我們會使用每個命令指定帳戶名稱和帳戶密鑰。 相反地,您可以使用對應的環境變數來儲存驗證認證: AZURE_STORAGE_ACCOUNTAZURE_STORAGE_KEY。 若要執行此動作,請使用EXPORT。

export AZURE_STORAGE_ACCOUNT=$storageAccount
export AZURE_STORAGE_KEY=$accountKey
az storage container list # Uses the environment variables to display the list of containers.

下列腳本會建立元數據字串,然後使用 az storage container metadata update 命令,再次使用該字串更新容器。

metadata="key=value pie=delicious" # Define metadata
az storage container metadata update \
    --name $container \
    --metadata $metadata # Update the metadata
az storage container metadata show \
    --name $containerName # Show the metadata

下列命令會使用 az storage container delete 命令來刪除單一具名容器,然後在迴圈中刪除多個容器。

az storage container delete \
    --name $container

取得包含特定前置詞的容器清單,並將結果儲存到變數中。

containerPrefix="learnbash"
containerList=$(az storage container list \
    --query "[].name" \
    --prefix $containerPrefix \
    --output tsv)

使用 --prefix 自變數刪除迴圈中的容器清單。

for row in $containerList
do
    tmpName=$(echo $row | sed -e 's/\r//g')
    az storage container delete \
    --name $tmpName 
done

錯誤處理

若要在命令傳回非零狀態時立即結束腳本,請執行下列命令:

set -e

如需設定殼層選項和其他說明的詳細資訊,請執行下列命令:

help set
help help

清除資源

當您完成本文時,請刪除資源群組及其內的所有資源。 --no-wait使用 自變數。

if [ $(az group exists --name $resourceGroup) = true ]; then 
   az group delete --name $resourceGroup -y  --no-wait
else
   echo The $resourceGroup resource group does not exist
fi

另請參閱