c# - 从 C# 调用 ARM 模板

标签 c# azure azure-resource-manager

我正在解决一个要求,我想从传递参数(如资源名称、资源位置等)的代码动态调用 ARM 模板,

我能够创建 ARM 模板。例如,为存储帐户创建了 ARM 模板,我有参数文件,其中包含要传递给模板的值。然而,我想从 C# 代码动态传递这些值并在 Azure 中配置资源。
从 Power shell 中我能够实现这一目标,但我希望从 C# 中也能实现同样的目标。

我可以探索的任何建议/技术链接。

最佳答案

我使用以下函数来使用 C# 部署 ARM 模板

private async Task DeployTemplate(string resourceGroupName, string deploymentName, JObject templateFileContents, JObject parameters)
        {
            var deployment = new Deployment
            {
                Properties = new DeploymentProperties
                {
                    Mode = DeploymentMode.Incremental,
                    Template = templateFileContents,
                    Parameters = parameters
                }
            };

            var serviceCredentials = await ApplicationTokenProvider.LoginSilentAsync(_tenantId, _clientId, _clientSecret);
            var resourceManagementClient = new ResourceManagementClient(serviceCredentials)
            {
                SubscriptionId = _subscriptionId
            };

            await resourceManagementClient.Deployments.CreateOrUpdateAsync(resourceGroupName, deploymentName, deployment);
        }

templateFileContents 通过此函数填充:

private static JObject GetJsonFileContents(string pathToJson)
        {
            var path = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), pathToJson);
            using (var file = File.OpenText(path))
            {
                using (var reader = new JsonTextReader(file))
                {
                    return (JObject)JToken.ReadFrom(reader);
                }
            }
        }

这就是我创建动态参数对象的方法:

var parameters = JObject.FromObject(
                new DbCloneArmParameters
                {
                    databaseName = new ArmParameterValue { Value = databaseName },
                    serverName = new ArmParameterValue { Value = servername },
                    location = new ArmParameterValue { Value = "westeurope" } }
                });

帮助类:

public class DbCloneArmParameters
    {
        public ArmParameterValue databaseName { get; set; }
        public ArmParameterValue serverName { get; set; }
        public ArmParameterValue location { get; set; }
    }

public class ArmParameterValue
    {
        public string Value { get; set; }
    }

关于c# - 从 C# 调用 ARM 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63767226/

相关文章:

c# - Linq 或存储过程 - 我应该选择哪一个?

c# - 评论接口(interface)、实现还是两者兼而有之?

c# - 如何将通用枚举中的多个转换器参数传递给 bool 转换器

azure - 尝试在 Visual Studio Code 中打开 Azure Cloud Shell 时出现 500 错误

azure - 使用 UWP 中的 Azure 移动客户端 LoginAsync 方法进行身份验证 - 未经授权

azure - 从现有 Azure 对象(例如 VM 或 VNET)创建 ARM 模板

azure - 无法理解 Azure 的角色 JSON

c# - 在没有 Thread.Sleep(300) 的情况下,如何在此类中获得真正的随机性?

php - 如何使用yaml模板创建azure容器注册表?

azure - 新-AzureRmResourceGroupDeployment : A parameter cannot be found that matches parameter name '_artifactsLocationSasToken'