gpt4 book ai didi

c# - 从 ARM 模板部署新的 Azure VM 时,无法格式化 .WithParameters() 的有效 JObject

转载 作者:行者123 更新时间:2023-12-03 04:09:41 25 4
gpt4 key购买 nike

目前,我在使用以 C# 编写的 Azure 函数从 ARM 模板部署 Azure VM 时遇到问题,同时使用 Newjonsoft.Json、Linq 库中的 JObject 为新 VM 提供参数。

JObject.FromObject() 方法以 "{"paramName": "paramValue"}" 格式制定参数,但我认为它需要制定为 "{"paramName": { "value": "paramValue"}。我不确定是否还需要指定 'contentVersion' 和 '$schema' ARM 模板参数才能使其正常工作。

到目前为止,我已经尝试使用动态变量来制定对象,然后将其转换为字符串并使用 JObject.Parse() 方法进行解析,但这只能产生与之前描述的相同的结果。

Azure 函数代码示例(并非所有代码):

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 Azure

IAzure azure = await
Authentication.AuthenticateWithAzure(azureVmDeploymentRequest.SubscriptionId);

// Get current datetime
string 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 SET

var parametersMain = new AzNewVmRequestArmParametersMain
{
parameters = parameters
};

var jParameters = JObject.FromObject(parameters);

// Deploy VM from ARM template if request is valid
var vmArmTemplateParams = new ARMTemplateDeploymentRequest
{
DeploymentName = "vmDeployTfLCP-" + Datetime,
ParametersObject = jParameters,
ResourceGroupName = azureVmDeploymentRequest.ResourceGroupName,
TemplateUri = Environment.GetEnvironmentVariable("VM_ARMTEMPLATE_URI"),
SasToken = Environment.GetEnvironmentVariable("STORAGE_ACCOUNT_SASTOKEN")
};

ARM 模板部署类代码示例(并非所有代码):

using Microsoft.Azure.Management.Fluent;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using System;
using Microsoft.Extensions.Logging;
using Microsoft.Rest.Azure;


// Formulate ARM template URI
var ArmTemplatePath = ARMTemplateDeploymentRequest.TemplateUri + ARMTemplateDeploymentRequest.SasToken;

deployment = azure.Deployments.Define(ARMTemplateDeploymentRequest.DeploymentName)
.WithExistingResourceGroup(ARMTemplateDeploymentRequest.ResourceGroupName)
.WithTemplateLink(ArmTemplatePath, "1.0.0.0")
.WithParameters(ARMTemplateDeploymentRequest.ParametersObject)
.WithMode(Microsoft.Azure.Management.ResourceManager.Fluent.Models.DeploymentMode.Incremental)
.Create();

作为预期结果,我希望代码能够简单地启动到 Azure 资源组的 ARM 模板部署,但目前它失败并显示以下消息:

'The request content was invalid and could not be deserialized: 'Error converting value "parameterValue" to type 'Microsoft.WindowsAzure.ResourceStack.Frontdoor.Data.Definitions.DeploymentParameterDefinition'. Path 'properties.parameters.vNetResourceGroup', line 8, position 48.'.'

最佳答案

根据我的测试,如果要使用动态变量来制定对象,我们需要创建一个新的JObject。例如我的模板.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();

关于c# - 从 ARM 模板部署新的 Azure VM 时,无法格式化 .WithParameters() 的有效 JObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57434148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com