簡體   English   中英

Azure生成資源組C#

[英]Azure Generate Resource Group C#

我希望你可以在代碼中幫助我,我很難生成創建資源組的代碼,但由於某種原因我無法理解什么是錯誤...我使用github的代碼: https: //github.com/Microsoft/azure-content/blob/master/articles/virtual-machines/arm-template-deployment.md我需要為工作中的項目工作這個例子...我將非常感激如果能幫我找到這段代碼的解決方案......

這里的代碼:

Program.cs中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.WindowsAzure;

namespace pruebaazure
{
    class Program
    {
        static void Main(string[] args)
        {
            var token = GetAuthorizationHeader();
            var credential = new Microsoft.WindowsAzure.TokenCloudCredentials("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxef", token);


            CreateResourceGroup(credential);
            Console.ReadLine();

            CreateTemplateDeployment(credential);
            Console.ReadLine();

            DeleteResourceGroup(credential);
            Console.ReadLine();


        }
        private static string GetAuthorizationHeader()
        {
            ClientCredential cc = new ClientCredential("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx8", "xxxxxxxK2");
            var context = new AuthenticationContext("https://login.windows.net/xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx4");
            var result = context.AcquireToken("https://management.azure.com/", cc);
            if (result == null)
            {
                throw new InvalidOperationException("Failed to obtain the JWT token");
            }

            string token = result.AccessToken;

            return token;
        }

        public async static void CreateResourceGroup(TokenCloudCredentials credential)
        {
            Console.WriteLine("Creating the resource group...");
            var resourceGroup = new ResourceGroup { Location = "West US" };
            using (var resourceManagementClient = new ResourceManagementClient(credential))
            {
                var rgResult = await resourceManagementClient.ResourceGroups.CreateOrUpdateAsync("mytestrg1", resourceGroup);
                Console.WriteLine(rgResult.StatusCode);
            }
        }

        public async static void CreateTemplateDeployment(TokenCloudCredentials credential)
        {
            Console.WriteLine("Creating the template deployment...");
            var deployment = new Deployment();
            deployment.Properties = new DeploymentProperties
            {
                Mode = DeploymentMode.Incremental,
                TemplateLink = new TemplateLink
                {
                    Uri = new Uri("https://xxxxxxxxxxxxya.blob.core.windows.net/templates/VirtualMachineTemplate.json").ToString()
                },
                ParametersLink = new ParametersLink
                {
                    Uri = new Uri("https://xxxxxxxxxxxxxya.blob.core.windows.net/templates/Parameters.json").ToString()
                }
            };
            using (var templateDeploymentClient = new ResourceManagementClient(credential))
                {
                var dpResult = await templateDeploymentClient.Deployments.CreateOrUpdateAsync("mytestrg1", "mytestdp1", deployment);
                Console.WriteLine(dpResult.StatusCode);
            }
        }

        public async static void DeleteResourceGroup(TokenCloudCredentials credential)
        {
            using (var resourceGroupClient = new ResourceManagementClient(credential))
            {
                var rgResult = await resourceGroupClient.ResourceGroups.DeleteAsync("mytestrg1");
                Console.WriteLine(rgResult.StatusCode);
            }
        }
    }
}

Parameters.json

{
  "contentVersion": "1.0.0.0",
  "parameters": { 
    "vmName": { "value": "mytestvm1" },
    "newStorageAccountName": { "value": "mytestsa1" },
    "storageAccountType": { "value": "Standard_LRS" },
    "publicIPaddressName": { "value": "mytestip1" },
    "location": { "value": "West US" },
    "vmStorageAccountContainerName": { "value": "vhds" },
    "vmSize": { "value": "Standard_A1" },
    "subscriptionId": { "value": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxef" },
    "vmSourceImageName": { "value": "sourceimgtest1" },
    "adminUserName": { "value": "mytestacct1" },
    "adminPassword": { "value": "mytestpass1" },
    "virtualNetworkName": { "value": "mytestvn1" },
    "dnsName": { "value": "mytestdns1" }, 
    "nicName": { "value": "mytestnic1" } 
  }
}

VirtualMachineTemplate.json

{
  "$schema": "http://schema.management.azure.com/schemas/2014-04-01-preview/VM.json",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "location": {
      "type": "String",
      "defaultValue": "West US",
      "allowedValues": [ "West US", "East US" ]
    },
    "newStorageAccountName": { "type": "string" },
    "storageAccountType": {
      "type": "string",
      "defaultValue": "Standard_LRS",
      "allowedValues": [ "Standard_LRS", "Standard_GRS" ]
    },
    "publicIPAddressName": { "type": "string" },
    "publicIPAddressType": {
      "type": "string",
      "defaultValue": "Dynamic",
      "allowedValues": [ "Dynamic" ]
    },
    "vmStorageAccountContainerName": {
      "type": "string",
      "defaultValue": "vhds"
    },
    "vmName": { "type": "string" },
    "vmSize": {
      "type": "string",
      "defaultValue": "Standard_A0",
      "allowedValues": [ "Standard_A0", "Standard_A1" ]
    },
    "vmSourceImageName": { "type": "string" },
    "adminUserName": { "type": "string" },
    "adminPassword": { "type": "securestring" },
    "virtualNetworkName": { "type": "string" },
    "addressPrefix": {
      "type": "string",
      "defaultValue": "10.0.0.0/16"
        },
        "subnet1Name": {
          "type": "string",
          "defaultValue": "Subnet-1"
        },
        "subnet2Name": {
          "type": "string",
          "defaultValue": "Subnet-2"
        },
        "subnet1Prefix": {
      "type": "string",
      "defaultValue": "10.0.0.0/24"
    },
    "subnet2Prefix": {
      "type": "string",
      "defaultValue": "10.0.1.0/24"
    },
    "dnsName": { "type": "string" },
    "subscriptionId": { "type": "string" },
    "nicName": { "type": "string" }
  },
  "resources": [
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[parameters('newStorageAccountName')]",
      "location": "[parameters('location')]",
      "properties": { "accountType": "[parameters('storageAccountType')]" }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Network/publicIPAddresses",
      "name": "[parameters('publicIPAddressName')]",
      "location": "[parameters('location')]",
      "properties": {
        "publicIPAllocationMethod": "[parameters('publicIPAddressType')]",
        "dnsSettings": { "domainNameLabel": "[parameters('dnsName')]" }
      }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Network/virtualNetworks",
      "name": "[parameters('virtualNetworkName')]",
      "location": "[parameters('location')]",
      "properties": {
        "addressSpace": { "addressPrefixes": [ "[parameters('addressPrefix')]" ] },
        "subnets": [
          {
            "name": "[parameters('subnet1Name')]",
            "properties": { "addressPrefix": "[parameters('subnet1Prefix')]"     }
          },
          {
            "name": "[parameters('subnet2Name')]",
            "properties": { "addressPrefix": "[parameters('subnet2Prefix')]"     }
          }
        ]
      }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Network/networkInterfaces",
      "name": "[parameters('nicName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[concat('Microsoft.Network/publicIPAddresses/', parameters('publicIPAddressName'))]",
        "[concat('Microsoft.Network/virtualNetworks/', parameters('virtualNetworkName'))]"
      ],
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', parameters('publicIPAddressName'))]"
              },
              "subnet": { "id": "[variables('subnet1Ref')]" }
            }
          }
        ]
      }
    },
    {
      "apiVersion": "2014-12-01-preview",
      "type": "Microsoft.Compute/virtualMachines",
      "name": "[parameters('vmName')]",
      "location": "[parameters('location')]",
      "dependsOn": [
        "[concat('Microsoft.Storage/storageAccounts/', parameters('newStorageAccountName'))]",
        "[concat('Microsoft.Network/networkInterfaces/', parameters('nicName'))]"
      ],
      "properties": {
        "hardwareProfile": { "vmSize": "[parameters('vmSize')]" },
        "osProfile": {
          "computername": "[parameters('vmName')]",
          "adminUsername": "[parameters('adminUsername')]",
          "adminPassword": "[parameters('adminPassword')]",
          "windowsProfile": { "provisionVMAgent": "true" }
        },
        "storageProfile": {
          "sourceImage": { "id": "[variables('sourceImageName')]" },
          "destinationVhdsContainer": "[concat('http://',parameters('newStorageAccountName'),'.blob.core.windows.net/',    parameters('vmStorageAccountContainerName'),'/')]"
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces',parameters('nicName'))]"
            }
          ]
        }
      }
    }
  ],
  "variables": {
    "sourceImageName": "[concat('/',parameters('subscriptionId'),'/services/images/',parameters('vmSourceImageName'))]",
    "vnetID": "[resourceId('Microsoft.Network/virtualNetworks',parameters('virtualNetworkName'))]",
    "subnet1Ref": [concat(variables('vnetID'),'/subnets/',parameters('subnet1Name'))]"
      }
   }
}

問題出在program.cs中

    public async static void CreateResourceGroup(TokenCloudCredentials credential)
    {
        Console.WriteLine("Creating the resource group...");
        var resourceGroup = new ResourceGroup { Location = "West US" };
        using (var resourceManagementClient = new ResourceManagementClient(credential))
        {
            var rgResult = await resourceManagementClient.ResourceGroups.CreateOrUpdateAsync("mytestrg1", resourceGroup);
            Console.WriteLine(rgResult.StatusCode);
        }
    }

在:

 (var resourceManagementClient = new ResourceManagementClient(credential)) 

錯誤是:

cannot convert from Microsoft.WindowsAzure.TokenCloudCredentials credentials to Microsoft.Rest.CerviceClientCredentials 

Console.WriteLine(rgResult.StatusCode); 

錯誤是:

ResourcesGroup does not contain the definition for "StatusCode" and no extension method "StatusCode" accepting a first argument of type 'ResourceGroup' Could be found 

public async static void CreateTemplateDeployment(TokenCloudCredentials credential) 

錯誤是相同的無法從Microsoft.WindowsAzure.TokenCloudCredentials憑據轉換為Microsoft.Rest.CerviceClientCredentials在這里

using (var templateDeploymentClient = new ResourceManagementClient(credential))
            {
                var dpResult = await templateDeploymentClient.Deployments.CreateOrUpdateAsync("mytestrg1", "mytestdp1", deployment);
                Console.WriteLine(dpResult.StatusCode);
            } 

並為此:

    public async static void DeleteResourceGroup(TokenCloudCredentials credential)
    {
        using (var resourceGroupClient = new ResourceManagementClient(credential))
        {
            var rgResult = await resourceGroupClient.ResourceGroups.DeleteAsync("mytestrg1");
            Console.WriteLine(rgResult.StatusCode);
        }
    }

我假設您正在使用"Microsoft.Azure.Management.Resources" nuget包的最新預覽版本,即版本= "3.3.0-preview"

從您的代碼和顯示的錯誤,您的問題的根本原因在於這行代碼:

var credential = new Microsoft.WindowsAzure.TokenCloudCredentials("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxef", token);

更清楚的是,Microsoft.WindowsAzure命名空間下的TokenCloudCredentials類不是ResourceManagementClient中ServiceClientCredentials抽象類的子類。

您應該使用Microsoft.Rest命名空間下的TokenCloudCredentials

因此您可以修復如下:

var credential = new Microsoft.Rest.TokenCloudCredentials(token);

您還可以參考以下GitHub存儲庫中的一些示例代碼: AzureResourceManagementSDKSample ,了解如何使用最新的“Microsoft.Azure.Management.Resources” nuget包創建/讀取/更新/刪除資源組以及創建資源組模板部署。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM