如何使用 azure .net SDK 或 Fluent API 验证 ARM 模板?

问题描述

如何使用 azure .net SDK 或 Fluent API 验证上传的 ARM 模板? 我想使用 azure .net SDK 或 Fluent API 验证我上传的 ARM 模板,例如 azure 门户吗? 如需参考,请参阅下图,如果 ARM 模板无效,则 azure 会显示消息,因此我想使用任何 .net API 或 REST API 实现相同的内容

enter image description here

@Jim 下面是我得到的错误

enter image description here

解决方法

如果您想验证您的手臂模板,请参考以下步骤

  1. 创建服务主体并将贡献者角色分配给 sp
az ad sp create-for-rbac -n "MyApp"
  1. 安装包
Install-Package Microsoft.Azure.Management.ResourceManager.Fluent -Version 1.34.0
  1. 代码
 string clientId = "23****9c";
            string clientSecret = "?s****/k";
            string tenantDomain = "";
            string subscription = "";
            var creds= SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId,clientSecret,tenantDomain,AzureEnvironment.AzureGlobalCloud);
            var restClient = RestClient.Configure()
                .WithEnvironment(AzureEnvironment.AzureGlobalCloud)
                .WithCredentials(creds)
                .WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
                .Build();


            ResourceManagementClient managementClient = new ResourceManagementClient(restClient);
            managementClient.SubscriptionId = subscription;

            //Validates whether the specified template is syntactically correct and will be accepted by Azure Resource Manager..
            DeploymentValidateResultInner res = await managementClient.Deployments.ValidateAsync("<groupName>","<deployName>",new DeploymentInner()
            {
                Location = "",Properties = new DeploymentProperties()
                {
                    ParametersLink = new ParametersLink("uri"),TemplateLink = new TemplateLink("")
                }
            });

            Console.WriteLine(res.Error.Message);

            // get changes that will be made by the deployment if executed at the scope of resource group
            WhatIfOperationResultInner res1 = await  managementClient.Deployments.WhatIfAsync("<groupName>",new DeploymentWhatIf() { 
                  Location="",Properties= new DeploymentWhatIfProperties() {
                       ParametersLink = new ParametersLink("uri"),TemplateLink = new TemplateLink("")
                   }
            });

            foreach (var change in res1.Changes) {
               // 
            }