亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 ARM 模板部署新的 Azure VM 時,無法格式化 .WithParameters()

從 ARM 模板部署新的 Azure VM 時,無法格式化 .WithParameters()

C#
躍然一笑 2023-08-20 10:59:42
目前,我在使用用 C# 編寫的 Azure 函數從 ARM 模板部署 Azure VM 時遇到問題,同時使用 Newjonsoft.Json、Linq 庫中的 JObject 為新 VM 提供參數。JObject.FromObject() 方法以 格式制定參數"{"paramName": "paramValue"}",但我認為它需要制定為"{"paramName": { "value": "paramValue"}。我不確定是否還需要指定“contentVersion”和“$schema”ARM 模板參數才能使其正常工作。到目前為止,我已經嘗試使用動態變量來制定對象,然后將其轉換為字符串并使用 JObject.Parse() 方法進行解析,但這只能產生與前面描述的相同的結果。Azure Function 代碼示例(并非所有代碼):using Microsoft.Azure.Management.Fluent;using Microsoft.Azure.WebJobs;using Microsoft.Extensions.Logging;using Microsoft.WindowsAzure.Storage.Table;using System.Threading.Tasks;using System;using Microsoft.Rest.Azure;using Newtonsoft.Json.Linq;// Authenticate with AzureIAzure azure = await     Authentication.AuthenticateWithAzure(azureVmDeploymentRequest.SubscriptionId);// Get current datetimestring Datetime = DateTime.Now.ToString("yyyy-MM-ddHHmmss");log.LogInformation("Initiating VM ARM Template Deployment");var parameters = azureVmDeploymentRequest.ToArmParameters(        subscriptionId: azureVmDeploymentRequest.SubscriptionId,        imageReferencePublisher: azureVmDeploymentRequest.ImageReferencePublisher    );// AzNewVmRequestArmParametersMain is a custom object containing the // parameters needed for the ARM template, constructed with GET SETvar parametersMain = new AzNewVmRequestArmParametersMain{    parameters = parameters};作為預期結果,我希望代碼能夠簡單地啟動到 Azure 資源組的 ARM 模板部署,但目前它失敗并顯示以下消息:'請求內容無效,無法反序列化:'將值“parameterValue”轉換為類型“Microsoft.WindowsAzure.ResourceStack.Frontdoor.Data.Definitions.DeploymentParameterDefinition”時出錯。路徑“properties.parameters.vNetResourceGroup”,第 8 行,位置 48?!??!?
查看完整描述

2 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

我能夠通過構造基于參數類型的類來解決該問題,并制定了一種將參數值映射到 ARM 參數類型的方法。


ARM模板參數類摘錄:


namespace FuncApp.MSAzure.ARMTemplates.ARMParaneterTypes

{

    public class ParameterValueString

    {

        public string Value { get; set; }

    }


    public class ParameterValueArray

    {

        public string[] Value { get; set; }

    }


    public class ParameterBoolValue

    {

        public bool Value { get; set; }

    }

}

映射類方法摘錄:


   public static AzNewVmRequestArmParameters ToArmParameters(

            this AzNewVmRequest requestContent,

            string adminUsername,

            string adminPassword

        )

    {


            return new AzNewVmRequestArmParameters

            {

                location = new ParameterValueString {

                    Value = requestContent.Location

                },

                adminUsername = new ParameterValueString

                {

                    Value = adminUsername

                },

                adminPassword = new ParameterValueString

                {

                    Value = adminPassword

                },

            };

        }


“AzNewVmRequestArmParameters”模型類摘錄:


namespace FuncApp.MSAzure.VirtualMachines

{

    public class AzNewVmRequestArmParameters

    {


        public ParameterValueString location { get; set; }


        public ParameterValueString adminUsername { get; set; }


        public ParameterValueString adminPassword { get; set; }


    }

}


有了這些,我就可以運行下面的代碼(簡化版)來制定一個有效的 jObject 變量,其中包含 API 可以準備的參數:


var parameters = azureVmDeploymentRequest.ToArmParameters(

   adminUsername: "azurevmadmin",

   adminPassword: "P@ssword123!"

);

var jParameters = JObject.FromObject(parameters);


查看完整回答
反對 回復 2023-08-20
?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

根據我的測試,如果要使用動態變量來制定對象,我們需要創建一個新的JObject。例如我的 template.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','myVNet123456')]", 

      "subnetRef": "[concat(variables('vnetID'),'/subnets/mySubnet')]"

    },

    "resources": [

      {

        "apiVersion": "2016-03-30",

        "type": "Microsoft.Network/publicIPAddresses",

        "name": "myPublicIPAddress123456",

        "location": "[resourceGroup().location]",

        "properties": {

          "publicIPAllocationMethod": "Dynamic",

          "dnsSettings": {

            "domainNameLabel": "myresourcegroupdns15896"

          }

        }

      },

      {

        "apiVersion": "2016-03-30",

        "type": "Microsoft.Network/virtualNetworks",

        "name": "myVNet123456",

        "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": "myNic562354",

        "location": "[resourceGroup().location]",

        "dependsOn": [

          "[resourceId('Microsoft.Network/publicIPAddresses/', 'myPublicIPAddress123456')]",

          "[resourceId('Microsoft.Network/virtualNetworks/', 'myVNet')]"

        ],

        "properties": {

          "ipConfigurations": [

            {

              "name": "ipconfig1",

              "properties": {

                "privateIPAllocationMethod": "Dynamic",

                "publicIPAddress": { "id": "[resourceId('Microsoft.Network/publicIPAddresses','myPublicIPAddress123456')]" },

                "subnet": { "id": "[variables('subnetRef')]" }

              }

            }

          ]

        }

      },

      {

        "apiVersion": "2016-04-30-preview",

        "type": "Microsoft.Compute/virtualMachines",

        "name": "myVM",

        "location": "[resourceGroup().location]",

        "dependsOn": [

          "[resourceId('Microsoft.Network/networkInterfaces/', 'myNic562354')]"

        ],

        "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','myNic562354')]"

              }

            ]

          }

        }

      }

    ]

  }

我的代碼


JObject parametesObjectv1 = new JObject(

                    new JProperty("adminUsername",

                        new JObject(

                            new JProperty("value", "azureuser")

                        )

                    ),

                    new JProperty("adminPassword",

                        new JObject(

                            new JProperty("value", "Azure12345678")

                        )

                    )

                );




       var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);

        var azure = Azure

                    .Configure()

                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)

                    .Authenticate(credentials)

                    .WithSubscription(subscriptionId);

        if (azure.ResourceGroups.Contain(resourceGroupName) == false)

        {

            var resourceGroup = azure.ResourceGroups.Define(resourceGroupName)

                            .WithRegion(resourceGroupLocation)

                            .Create();

        }

        Console.WriteLine("start");

        var deployment = azure.Deployments.Define(deploymentName)

                    .WithExistingResourceGroup(resourceGroupName)

                    .WithTemplateLink(pathToTemplateFile, "1.0.0.0")

                    .WithParameters(parametesObjectv1)

                    .WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)

                    .Create();

另外,如果你不想使用動態變量,你可以直接提供parameter.json和template.json的url來創建資源


var deployment = azure.Deployments.Define(deploymentName)

                    .WithExistingResourceGroup(resourceGroupName)

                    .WithTemplateLink(pathToTemplateFile, "1.0.0.0")

                    .WithParametersLink(pathToJsonFile, "1.0.0.0")

                    .WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)

                    .Create();


查看完整回答
反對 回復 2023-08-20
  • 2 回答
  • 0 關注
  • 135 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號