本文說明如何使用 C# 部署 Azure Resource Manager 範本。 您建立的範本會在具有單一子網的新虛擬網路中部署執行 Windows Server 的單一虛擬機。
如需虛擬機資源的詳細描述,請參閱 Azure Resource Manager 範本中的虛擬機。 如需範本中所有資源的詳細資訊,請參閱 Azure Resource Manager 範本逐步解說。
執行這些步驟大約需要 10 分鐘的時間。
建立 Visual Studio 專案
在此步驟中,您會確定已安裝Visual Studio,並建立用來部署範本的控制台應用程式。
- 如果您尚未安裝,請安裝 Visual Studio。 在 [工作負載] 頁面上選取 [.NET 桌面開發 ],然後按兩下 [ 安裝]。 在摘要中,您可以看到會自動為您選取 .NET Framework 4 - 4.6 開發工具 。 如果您已安裝 Visual Studio,您可以使用 Visual Studio 啟動器來新增 .NET 工作負載。
- 在 Visual Studio 中,按兩下 [ 檔案>新>專案]。
- 在 [範本>Visual C#] 中,選取 [控制台應用程式][.NET Framework],輸入 myDotnetProject 以取得專案的名稱,選取專案的位置,然後按兩下 [ 確定]。
安裝套件
NuGet 套件是安裝完成這些步驟所需連結庫的最簡單方式。 若要取得 Visual Studio 中所需的連結庫,請執行下列步驟:
按兩下 [工具>][Nuget 套件管理員],然後按兩下 [ 套件管理員主控台]。
在控制台中輸入下列命令:
Install-Package Microsoft.Azure.Management.Fluent Install-Package WindowsAzure.Storage
建立檔案
在此步驟中,您會建立範本檔案,以部署資源,以及提供參數值給範本的參數檔案。 您也會建立用來執行 Azure Resource Manager 作業的授權檔案。
建立範本檔案
在 [方案總管] 中,以滑鼠右鍵按兩下 myDotnetProject>[新增>專案],然後選取 [Visual C# 專案中的文字檔]。 將檔案命名 CreateVMTemplate.json,然後按兩下 [ 新增]。
將此 JSON 程式代碼新增至您建立的檔案:
{ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "adminUsername": { "type": "string" }, "adminPassword": { "type": "securestring" } }, "variables": { "vnetID": "[resourceId('Microsoft.Network/virtualNetworks','myVNet')]", "subnetRef": "[concat(variables('vnetID'),'/subnets/mySubnet')]", }, "resources": [ { "apiVersion": "2016-03-30", "type": "Microsoft.Network/publicIPAddresses", "name": "myPublicIPAddress", "location": "[resourceGroup().location]", "properties": { "publicIPAllocationMethod": "Dynamic", "dnsSettings": { "domainNameLabel": "myresourcegroupdns1" } } }, { "apiVersion": "2016-03-30", "type": "Microsoft.Network/virtualNetworks", "name": "myVNet", "location": "[resourceGroup().location]", "properties": { "addressSpace": { "addressPrefixes": [ "10.0.0.0/16" ] }, "subnets": [ { "name": "mySubnet", "properties": { "addressPrefix": "10.0.0.0/24" } } ] } }, { "apiVersion": "2016-03-30", "type": "Microsoft.Network/networkInterfaces", "name": "myNic", "location": "[resourceGroup().location]", "dependsOn": [ "[resourceId('Microsoft.Network/publicIPAddresses/', 'myPublicIPAddress')]", "[resourceId('Microsoft.Network/virtualNetworks/', 'myVNet')]" ], "properties": { "ipConfigurations": [ { "name": "ipconfig1", "properties": { "privateIPAllocationMethod": "Dynamic", "publicIPAddress": { "id": "[resourceId('Microsoft.Network/publicIPAddresses','myPublicIPAddress')]" }, "subnet": { "id": "[variables('subnetRef')]" } } } ] } }, { "apiVersion": "2016-04-30-preview", "type": "Microsoft.Compute/virtualMachines", "name": "myVM", "location": "[resourceGroup().location]", "dependsOn": [ "[resourceId('Microsoft.Network/networkInterfaces/', 'myNic')]" ], "properties": { "hardwareProfile": { "vmSize": "Standard_DS1" }, "osProfile": { "computerName": "myVM", "adminUsername": "[parameters('adminUsername')]", "adminPassword": "[parameters('adminPassword')]" }, "storageProfile": { "imageReference": { "publisher": "MicrosoftWindowsServer", "offer": "WindowsServer", "sku": "2012-R2-Datacenter", "version": "latest" }, "osDisk": { "name": "myManagedOSDisk", "caching": "ReadWrite", "createOption": "FromImage" } }, "networkProfile": { "networkInterfaces": [ { "id": "[resourceId('Microsoft.Network/networkInterfaces','myNic')]" } ] } } } ] }
儲存 CreateVMTemplate.json 檔案。
建立參數檔案
若要在範本中指定資源參數的值,您可以建立包含值的參數檔案。
在 [方案總管] 中,以滑鼠右鍵按兩下 myDotnetProject>[新增>專案],然後選取 [Visual C# 專案中的文字檔]。 將檔案命名 Parameters.json,然後按兩下 [ 新增]。
將此 JSON 程式代碼新增至您建立的檔案:
{ "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json", "contentVersion": "1.0.0.0", "parameters": { "adminUserName": { "value": "azureuser" }, "adminPassword": { "value": "Azure12345678" } } }
儲存 Parameters.json 檔案。
建立授權檔案
部署範本之前,請確定您可以存取 Active Directory 服務主體。 從服務主體取得令牌,以向 Azure Resource Manager 驗證要求。 您也應該記錄應用程式標識碼、驗證金鑰,以及授權檔中所需的租用戶標識碼。
在 [方案總管] 中,以滑鼠右鍵按兩下 myDotnetProject>[新增>專案],然後選取 [Visual C# 專案中的文字檔]。 將檔案命名為 azureauth.properties,然後按兩下 [ 新增]。
新增這些授權屬性:
subscription=<subscription-id> client=<application-id> key=<authentication-key> tenant=<tenant-id> managementURI=https://management.core.windows.net/ baseURL=https://management.azure.com/ authURL=https://login.windows.net/ graphURL=https://graph.microsoft.com/
將 subscription-id> 取代<為您的訂用帳戶標識碼、<將 application-id> 取代為 Active Directory 應用程式識別碼、<將 authentication-key 取代為應用程式密鑰>,並將 <tenant-id> 取代為租使用者識別符。
儲存 azureauth.properties 檔案。
在名為 AZURE_AUTH_LOCATION 的 Windows 中設定環境變數,其中包含您所建立授權檔案的完整路徑,例如,您可以使用下列 PowerShell 命令:
[Environment]::SetEnvironmentVariable("AZURE_AUTH_LOCATION", "C:\Visual Studio 2019\Projects\myDotnetProject\myDotnetProject\azureauth.properties", "User")
建立管理用戶端
開啟您所建立項目的Program.cs檔案。 然後,將這些 using 語句新增至檔案頂端的現有 語句:
using Microsoft.Azure.Management.Compute.Fluent; using Microsoft.Azure.Management.Compute.Fluent.Models; using Microsoft.Azure.Management.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob;
若要建立管理用戶端,請將此程式代碼新增至Main方法:
var credentials = SdkContext.AzureCredentialsFactory .FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription();
建立資源群組
若要指定應用程式的值,請將程式代碼新增至 Main 方法:
var groupName = "myResourceGroup";
var location = Region.USWest;
var resourceGroup = azure.ResourceGroups.Define(groupName)
.WithRegion(location)
.Create();
建立記憶體帳戶
範本和參數會從 Azure 中的記憶體帳戶部署。 在此步驟中,您會建立帳戶並上傳檔案。
若要建立帳戶,請將此程式碼新增至主方法中:
string storageAccountName = SdkContext.RandomResourceName("st", 10);
Console.WriteLine("Creating storage account...");
var storage = azure.StorageAccounts.Define(storageAccountName)
.WithRegion(Region.USWest)
.WithExistingResourceGroup(resourceGroup)
.Create();
var storageKeys = storage.GetKeys();
string storageConnectionString = "DefaultEndpointsProtocol=https;"
+ "AccountName=" + storage.Name
+ ";AccountKey=" + storageKeys[0].Value
+ ";EndpointSuffix=core.windows.net";
var account = CloudStorageAccount.Parse(storageConnectionString);
var serviceClient = account.CreateCloudBlobClient();
Console.WriteLine("Creating container...");
var container = serviceClient.GetContainerReference("templates");
container.CreateIfNotExistsAsync().Wait();
var containerPermissions = new BlobContainerPermissions()
{ PublicAccess = BlobContainerPublicAccessType.Container };
container.SetPermissionsAsync(containerPermissions).Wait();
Console.WriteLine("Uploading template file...");
var templateblob = container.GetBlockBlobReference("CreateVMTemplate.json");
templateblob.UploadFromFileAsync("..\\..\\CreateVMTemplate.json").Result();
Console.WriteLine("Uploading parameters file...");
var paramblob = container.GetBlockBlobReference("Parameters.json");
paramblob.UploadFromFileAsync("..\\..\\Parameters.json").Result();
部署範本
從建立的記憶體帳戶部署範本和參數。
若要部署範本,請將此程式代碼新增至Main方法:
var templatePath = "https://" + storageAccountName + ".blob.core.windows.net/templates/CreateVMTemplate.json";
var paramPath = "https://" + storageAccountName + ".blob.core.windows.net/templates/Parameters.json";
var deployment = azure.Deployments.Define("myDeployment")
.WithExistingResourceGroup(groupName)
.WithTemplateLink(templatePath, "1.0.0.0")
.WithParametersLink(paramPath, "1.0.0.0")
.WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
.Create();
Console.WriteLine("Press enter to delete the resource group...");
Console.ReadLine();
刪除資源
因為您需支付 Azure 中使用的資源費用,所以刪除不再需要的資源一律是很好的作法。 您不需要從資源群組個別刪除每個資源。 刪除資源群組後,其所有資源會自動刪除。
若要刪除資源群組,請將此程式代碼新增至 Main 方法:
azure.ResourceGroups.DeleteByName(groupName);
執行應用程式
此主控台應用程式需要大約五分鐘的時間才能從頭到尾完全執行。
若要執行主控台應用程式,請按兩下 [ 啟動]。
在您按 Enter 開始刪除資源之前,可能需要幾分鐘的時間,才能確認在 Azure 入口網站中建立資源。 按兩下部署狀態以查看部署的相關信息。
後續步驟
- 如果部署發生問題,下一個步驟是使用 Azure Resource Manager 針對常見的 Azure 部署錯誤進行疑難解答。
- 瞭解如何檢閱 使用 C# 部署 Azure 虛擬機,以部署虛擬機及其支持資源。