Reputation: 13
I am working on a requirement where I want to call ARM Template dynamically from code passing parameters, like Resource Name, Resource Location etc.,
I am able to create ARM template. For example, created ARM Template for storage account and I have parameter file with values to pass to the template. However these values I want to pass from c# code dynamically and provision the resource in Azure.
From Power shell I am able to achieve this but I want the same to be done from c#.
Any suggestions/technical links that I can explore.
Upvotes: 0
Views: 2448
Reputation: 557
I use the following function to deploy an ARM Template using c#
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);
}
The templateFileContents get filled by this function:
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);
}
}
}
This is how I create a dynamic parameters object:
var parameters = JObject.FromObject(
new DbCloneArmParameters
{
databaseName = new ArmParameterValue { Value = databaseName },
serverName = new ArmParameterValue { Value = servername },
location = new ArmParameterValue { Value = "westeurope" } }
});
Helper classes:
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; }
}
Upvotes: 3
Reputation: 169
I think Microsoft.Azure.Management.Fluent solves your problem.
If you look at Microsoft documentation "Deploy an Azure Virtual Machine using C# and a Resource Manager template", it walks you through deploying a VM using a template file from C#. The documentation could be used as a starting point to deploy any ARM template to Azure.
Upvotes: 0