使用 GitHub Copilot 協助 Azure CLI 和 PowerShell
儘管宣告式 IaC 工具如 Bicep 興起,命令列工具如 Azure CLI 和 Azure PowerShell 仍是雲端工程師不可或缺的工具。 有些任務無法完全套入範本:部署前檢查、資料遷移、操作手冊、非計畫故障排除,以及涉及條件邏輯或迴圈的自動化。
當團隊需要快速處理事情時,命令列(CLI)腳本也常常是第一個會用的工具。 你能寫出和執行腳本的速度很重要。 這正是 GitHub Copilot 立即帶來價值的地方。 你不用在文件裡找正確的指令和參數,只要用白話描述你想要的東西,Copilot 就會產生腳本。
Azure CLI 與 Azure PowerShell
在產生腳本之前,了解該用哪種工具會很有幫助。
Azure CLI(az)是一款跨平台命令列工具,可在 Windows、macOS 及 Linux 上運行。 它的輸出預設是 JSON,方便輸入其他工具。 Azure CLI 廣泛應用於 bash 腳本、基於 Linux 的 CI/CD 代理程式,以及具備 Linux 或 DevOps 背景的團隊。
Azure PowerShell(Az模組) 使用 PowerShell 語言,並可透過 PowerShell 7+ 在 Windows、macOS 及 Linux 上運行。 其輸出為結構化的 .NET 物件,使其在複雜邏輯、過濾及與其他 Microsoft 服務 整合方面非常強大。 PowerShell 似乎受到 Windows 重度團隊和系統管理員的偏好。
這兩個工具都涵蓋相同的 Azure 作業。 選擇它們主要是取決於你的團隊最熟悉哪種語言,以及腳本運行的環境。 GitHub Copilot 能流暢地處理這兩種語言,並且能在兩者之間進行轉換。
使用 Copilot 生成 Azure CLI 腳本
從簡單開始
對於簡單的資源創建,直接的提示效果很好。 Copilot 知道 az 指令結構,並能為常見操作產生正確的語法。
範例提示可以是這樣的:
Generate an Azure CLI command to create a resource group called "rg-webapp-prod" in the West Europe region, tagged with Environment=Production and Owner=platform-team.
GitHub Copilot 的回應可能類似:
az group create \
--name rg-webapp-prod \
--location westeurope \
--tags Environment=Production Owner=platform-team
對於單一指令,語法很直接。 真正的價值在於你請 GitHub Copilot 建立一個包含多步驟、變數和錯誤處理的完整腳本。
建立完整的配置腳本
在這種更進階的方法中,你的提示可能會包含更多細節,例如這裡的範例:
Generate an Azure CLI bash script that provisions the following resources:
- Resource group: rg-iaclab in East US
- VNet: vnet-iaclab with address space 10.0.0.0/16
- Subnet: snet-app at 10.0.1.0/24
- NSG: nsg-app with a rule denying all inbound internet traffic
except HTTPS (port 443)
- Associate the NSG with snet-app
Requirements:
- Use variables at the top for all configurable values
- Check if the resource group already exists before creating it
- Print a status message after each successful resource creation
- Exit immediately if any command fails (set -e)
- Tag all resources with Environment=Training and Owner=lab-user
Copilot 會產生一個包含乾淨變數區塊、冪등 性檢查及狀態訊息的腳本。 這裡的關鍵提示技巧包括:
- 變數置於頂端:防止硬編碼值散落在腳本中
- 建立前檢查是否存在:讓指令碼具備冪等性 (可安全重新執行)
-
故障時退出(
set -e):防止靜默失敗傳播
新增冪等性
冪性指的是腳本產生相同的結果,無論是執行一次還是 10 次。 這對於自動化腳本來說至關重要,因為這些腳本可能在排程中執行,或作為 CI/CD 管線的一部分。
以下是使用提示詞為您的指令碼產生加入冪等性的範例:
Refactor this script so that each resource creation command first checks whether the resource already exists. If it exists, print "already exists — skipping" and continue. If it does not exist, create it.
Use az [resource] show with a 2>/dev/null check to test for existence.
Copilot 會將每個 az ... create 指令包裹在存在檢查模式中:
if ! az network vnet show --name "$VNET_NAME" --resource-group "$RG_NAME" \
--query id -o tsv 2>/dev/null; then
echo "Creating VNet: $VNET_NAME..."
az network vnet create \
--name "$VNET_NAME" \
--resource-group "$RG_NAME" \
--address-prefix "$VNET_PREFIX"
echo "VNet created successfully."
else
echo "VNet $VNET_NAME already exists — skipping."
fi
新增參數驗證
另一個有用的使用情境是將參數驗證作為提示的一部分。 請參考此處範例:
Add a validation block at the top of the script that:
- Checks that the az CLI is installed and the user is logged in
- Verifies the target subscription is set correctly
- Accepts RESOURCE_GROUP, LOCATION, and OWNER as command-line arguments
and exits with a usage message if they are not provided
這種模式使腳本適合用於自動化管線,因為輸入來自環境變數或 CI/CD 參數,而非硬編碼值。
使用 GitHub Copilot 生成 Azure PowerShell 腳本
同樣的自然語言方法適用於 (Azure) PowerShell。 Copilot 能理解 Az 模組中的命令指令 (cmdlet),並產生自然的 PowerShell 語法,而不是直譯 CLI 語法。
透過在提示詞中包含所需的腳本語言,您可以縮小 GitHub Copilot 的範圍:
Generate an Azure PowerShell script that:
- Connects to Azure using a service principal (client ID, client secret,
tenant ID passed as parameters)
- Creates a resource group "rg-iaclab" in East US if it does not already exist
- Creates a Storage Account with Standard_LRS SKU, HTTPS-only access,
and blob soft delete enabled (30 days)
- Outputs the storage account's primary connection string at the end
Use proper error handling with try/catch blocks.
GitHub Copilot 以清晰的 PowerShell 語法回應,理解 Azure 資源與參數:
param(
[Parameter(Mandatory=$true)][string]$TenantId,
[Parameter(Mandatory=$true)][string]$ClientId,
[Parameter(Mandatory=$true)][string]$ClientSecret,
[string]$Location = "eastus",
[string]$ResourceGroupName = "rg-iaclab",
[string]$StorageAccountName = "stiaclab$(Get-Random -Maximum 9999)"
)
# Connect using service principal
$SecureSecret = ConvertTo-SecureString $ClientSecret -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($ClientId, $SecureSecret)
try {
Connect-AzAccount -ServicePrincipal -Credential $Credential -Tenant $TenantId
Write-Host "Connected to Azure successfully." -ForegroundColor Green
} catch {
Write-Error "Failed to connect to Azure: $_"
exit 1
}
# Create resource group if it does not exist
$RG = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue
if (-not $RG) {
Write-Host "Creating resource group: $ResourceGroupName..."
New-AzResourceGroup -Name $ResourceGroupName -Location $Location `
-Tag @{ Environment = "Training"; Owner = "lab-user" }
}
請注意,Copilot 自然產生 PowerShell 慣用語模式:param() 區塊、try/catch、-ErrorAction SilentlyContinue,以及 $(...) 擴展語法。 它不會嘗試在 PowerShell 裡複製 bash 模式。
在 CLI 和 PowerShell 之間進行翻譯
GitHub Copilot 在基礎架構工作中最實用的用途之一是將腳本在工具間轉換。 常見案例如下:
- 一個由以 Linux 為中心的團隊撰寫的腳本,必須在 Windows 上執行
- 文件範例在 CLI 裡,但你們團隊使用 PowerShell
- 你想把所有自動化標準化成一種語言
這樣的轉換提示可以像這樣:
Translate the following Azure CLI bash script to Azure PowerShell.
Use Az module cmdlets throughout. Preserve:
- The same variable/parameter names where possible
- All error handling logic
- The existence check pattern before each resource creation
- Tag application on all resources
Do not add features that are not in the original script.
[paste your CLI script here]
指令 Do not add features that are not in the original 很重要。 沒有它,Copilot 有時會新增日誌、遙測或額外功能,這些功能是未被要求的。 這使得比較兩個文字並驗證其等效性變得更困難。
主要 CLI-to-PowerShell 等價項目
了解映射能幫助你驗證 Copilot 的翻譯:
| Azure CLI | Azure PowerShell |
|---|---|
az group create |
New-AzResourceGroup |
az group show |
Get-AzResourceGroup |
az network vnet create |
New-AzVirtualNetwork |
az network nsg create |
New-AzNetworkSecurityGroup |
az vm create |
New-AzVM |
az storage account create |
New-AzStorageAccount |
az keyvault create |
New-AzKeyVault |
--query + --output tsv |
Select-Object + .PropertyName |
$? (出口代碼檢查) |
$? 或 try/catch |
Copilot 協助的 CLI 工作實用模式
為不熟悉的資源產生指令
即使是有經驗的 Azure 工程師,也會遇到他們之前接觸過的 Azure 資源類型。 Copilot 會省去文件查閱:
在提示中清楚標示 Azure 資源類型,就足以讓 Copilot 產生正確的指令:
Generate an Azure CLI command to create an Azure Container Registry with
Premium SKU, geo-replication to West Europe, admin account disabled,
and a system-assigned managed identity. Output the login server at the end.
Copilot 會產生正確的 az acr create 指令,並搭配正確的旗標名稱。 包括容易被遺忘的旗標,如 --sku、 --admin-enabled false和 --identity [system]。
建立清理腳本
清理腳本在訓練環境與開發中至關重要。 Copilot 快速生成這些檔案。 這類提示的範例可能如下:
Generate an Azure CLI script that:
- Lists all resource groups with the tag Environment=Training
- Prints each group name and asks for confirmation before deleting
- Deletes confirmed groups with --no-wait for speed
- Reports how many groups were deleted at the end
產生跨訂閱腳本
企業環境通常依賴多個 Azure 訂閱。 有了 GitHub Copilot,這種額外的複雜性變得容易處理。 請將該規格納入你的提示中,如圖所示:
Generate an Azure CLI script that iterates over all subscriptions in my tenant,
checks each one for storage accounts that have public blob access enabled,
and outputs a CSV report with: SubscriptionName, ResourceGroup, StorageAccountName, Location.
Copilot 正確地使用 az account list 和 az account set 產生迴圈結構,並處理許多工程師在從零開始撰寫代碼時容易遇到的訂閱上下文切換問題。
重點摘要
- Azure CLI 和 PowerShell 對於無法符合宣告式範本的操作和條件自動化來說是必不可少的。
- 有效的 CLI 提示包括變數區塊、存在性檢查、錯誤處理及標籤要求。
- Copilot 會在 CLI 和 PowerShell 中產生符合語境的輸出,而不是機械式地轉換其中一個為另一個。
- 使用轉換模式(「將此 CLI 腳本轉成 PowerShell,保留所有邏輯,不新增功能」)以確保可靠的跨工具轉換。
- 使用 CLI 來處理操作性和條件性任務:使用 Bicep 來管理長期的基礎設施狀態。