在本教學課程中,您會使用適用於 Go 的 Azure SDK 來部署 Azure Resource Manager 範本。
Azure Resource Manager 是 Azure 的部署和管理服務。 它可讓您建立、更新及刪除 Azure 帳戶中的資源。 Azure Resource Manager 範本會以宣告方式將基礎結構描述為 JSON 檔中的程式碼。
在這個教學結束時,你會用 Go 撰寫並部署 Azure 資源管理器範本。
先決條件
- Azure 訂用帳戶:如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶。
建立新模組
在這個區塊中,你會建立一個新的 Go 模組,並安裝所需的 Azure SDK 套件。 接著你建立主應用程式檔案,並加入部署 Azure Resource Manager 範本的程式碼。
建立一個名為
deployARM-how-to. 的新目錄。 然後切換到該目錄。mkdir deployARM-how-to cd deployARM-how-to執行
go mod init命令以建立go.mod和go.sum檔案。go mod init deployARM-how-toAzure SDK for Go 包含多個用於 Azure 的套件。 這個教學需要
azcore/to、azidentity和armresources套件。執行
go get命令以下載這些套件:go get github.com/Azure/azure-sdk-for-go/sdk/azcore/to go get github.com/Azure/azure-sdk-for-go/sdk/azidentity go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources建立名為
main.go的檔案。touch main.go在編輯器中開啟
main.go,新增以下程式碼,該程式碼可認證 Azure、建立資源群組,並部署 Azure 資源管理器範本:package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources" ) const ( resourceGroupName = "deployARM-how-to" resourceGroupLocation = "eastus" deploymentName = "deployARM-how-to" templateFile = "template.json" ) var ( ctx = context.Background() ) // Read a JSON file from the given path. func readJSON(path string) (map[string]interface{}, error) { data, err := os.ReadFile(path) if err != nil { log.Fatalf("failed to read file: %v", err) } contents := make(map[string]interface{}) _ = json.Unmarshal(data, &contents) return contents, nil } func main() { subscriptionId := os.Getenv("AZURE_SUBSCRIPTION_ID") // Authenticate to Azure cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Fatalf("failed to obtain a credential: %v", err) } // Create a resource group. client, err := armresources.NewResourceGroupsClient(subscriptionId, cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } resp, err := client.CreateOrUpdate(context.Background(), resourceGroupName, armresources.ResourceGroup{ Location: to.Ptr(resourceGroupLocation), }, nil) if err != nil { log.Fatalf("failed to obtain a response: %v", err) } log.Printf("resource group ID: %s\n", *resp.ResourceGroup.ID) // Read the template file. template, err := readJSON(templateFile) if err != nil { return } // Deploy the Azure Resource Manager template. deploymentsClient, err := armresources.NewDeploymentsClient(subscriptionId, cred, nil) if err != nil { log.Fatalf("failed to create client: %v", err) } deploy, err := deploymentsClient.BeginCreateOrUpdate( ctx, resourceGroupName, deploymentName, armresources.Deployment{ Properties: &armresources.DeploymentProperties{ Template: template, Mode: to.Ptr(armresources.DeploymentModeIncremental), }, }, nil, ) if err != nil { log.Fatalf("failed to deploy template: %v", err) } fmt.Println(deploy) }
建立 Azure Resource Manager 範本
在目錄中
deployARM-how-to建立另一個名為template.json的檔案。打開檔案
template.json並新增以下 Azure Resource Manager 範本程式碼,建立 Azure 儲存帳號:{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { }, "functions": [], "variables": {}, "resources": [{ "name": "<StorageAccountName>", "type": "Microsoft.Storage/storageAccounts", "apiVersion": "2021-04-01", "tags": { "displayName": "<StorageAccountDisplayName>" }, "location": "EastUS", "kind": "StorageV2", "sku": { "name": "Premium_LRS", "tier": "Premium" } }], "outputs": {} }將
<StorageAccountName>和<StorageAccountDisplayName>替換為有效的儲存體名稱值。
欲了解更多關於 Azure Resource Manager 範本的資訊,請參閱 Azure Resource Manager 範本總覽。
登入 Azure
本文中的程式碼會使用 Go 的 Azure 身分識別模組中的 DefaultAzureCredential 類型來向 Azure 進行驗證。
DefaultAzureCredential 支援許多認證類型,以使用 OAuth 搭配 Microsoft Entra ID 向 Azure 進行驗證。 在本文中,您會使用登入 Azure CLI 時所用的使用者認證。
如果您尚未登入,請登入 Azure CLI:
az login
如果你的帳戶有多個訂閱,請使用 az account list 指令取得這些訂閱清單。 使用 az account set 指令來設定有效訂閱。 透過設定有效訂閱,你確保本文後面執行的任何 CLI 指令都會與你預期的訂閱相符。
備註
本地執行時, DefaultAzureCredential 也支援 Azure Developer CLI(AZD)登入憑證,或是在環境變數中設定的 Azure 服務主體。 若要深入瞭解所有支援的認證類型,請參閱 使用 Go 的 Azure 身分識別模組進行 Azure 驗證。
執行應用程式
在部署範本之前,您必須先將 Azure 訂用帳戶識別碼定義為環境變數。
要取得訂閱 ID,請執行以下 az account show 指令。
az account show --query id --output tsv用你的訂閱 ID 設定
AZURE_SUBSCRIPTION_ID環境變數。 使用您的訂用帳戶 ID 來取代<AzureSubscriptionId>。export AZURE_SUBSCRIPTION_ID=<AzureSubscriptionId>執行
go run部署範本的指令:go run main.go
Troubleshoot
如果儲存帳號部署失敗,請確認你使用的 儲存名稱值是否有效。 儲存體帳戶名稱的長度必須介於 3 到 24 個字元之間,且只能包含小寫字母和數字。
若程式回傳與認證或授權相關的錯誤,請檢查以下項目:
如果錯誤以時間戳記開頭,並顯示下列文字:「無法取得回應:DefaultAzureCredential:無法取得權杖。」,請確定您已依照先前的指示登入 Azure CLI。
如果錯誤是授權或禁止錯誤 (狀態碼 401 或 403),請確定您的使用者帳戶位於 Azure 角色中,以授與其建立資源群組和在訂用帳戶上新增資源的權限。 範例包括 參與者 或 擁有者Azure 內建角色。 若要瞭解如何將 Azure 角色指派給使用者,請參閱 使用 Azure CLI 指派 Azure 角色。
如需更詳細的疑難排解指引,請參閱 針對 Azure 身分識別驗證問題進行疑難排解。
驗證 Azure 上的資源
你可以使用幾個 Azure CLI 指令來驗證資源是否成功在 Azure 上建立。 下列命令是一些範例。
要驗證資源群組是否存在,請執行 az 群組存在 指令。
az group exists --name deployARM-how-to
你可以使用 az resource list 指令列出群組中的資源。
az resource list --resource-group deployARM-how-to
你可以使用 az deployment group show 指令來查看部署結果(outputResources)和屬性。
az deployment group show -g deployARM-how-to -n deployARM-how-to
清理資源
Azure 中的資源可能會產生持續收費。 務必整理你在這篇文章中建立的資源。
以完整模式部署空白範本會刪除資源群組內的所有資源。 這是清除資源而不刪除資源群組本身的簡潔方法。
建立名為 的新空白範本
empty-template.json。在編輯器中開啟
empty-template.json並加入以下程式碼:{ "$schema": "https://schema.management.azure.com/schemas/2019-08-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": {}, "variables": {}, "resources": [], "outputs": {} }開啟您的
main.go檔案。將常數值更新
templateFile為empty-template.json。const ( resourceGroupName = "deployARM-how-to" resourceGroupLocation = "eastus" deploymentName = "deployARM-how-to" templateFile = "empty-template.json" )將部署時間從 增量 改為 完成 ,方法是將部署 模式 屬性改為
DeploymentModeComplete。 若要深入瞭解部署模式,請參閱 Azure Resource Manager 部署模式。deploy, err = deploymentsClient.BeginCreateOrUpdate( ctx, resourceGroupName, deploymentName, armresources.Deployment{ Properties: &armresources.DeploymentProperties{ Template: template, Mode: to.Ptr(armresources.DeploymentModeComplete), //Deployment Mode is here }, }, nil, )執行
go run命令來部署空白範本,並刪除您先前建立的儲存體帳戶。go run main.go
你可以不使用部署,而是透過執行以下 Azure CLI 指令刪除資源群組及其所有資源:
az group delete --resource-group deployARM-how-to