Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active December 9, 2021 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/e460a6b166f59fd4d791421dbd09590b to your computer and use it in GitHub Desktop.
Save gsscoder/e460a6b166f59fd4d791421dbd09590b to your computer and use it in GitHub Desktop.
C# sample that demonstrates programmatic JSON AzureRM template export
// requires Microsoft.IdentityModel.Clients.ActiveDirectory 5.29
// Microsoft.Azure.Management.ResourceManager 3.15.1-preview
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
class CustomLoginCredentials : ServiceClientCredentials
{
string _authnToken { get; set; }
public override void InitializeServiceClient<T>(ServiceClient<T> client)
{
var authenticationContext = new AuthenticationContext("https://login.windows.net/YOUR_TENANT_ID");
var credential = new ClientCredential(clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET");
var result = authenticationContext.AcquireTokenAsync(resource: "https://management.core.windows.net/", clientCredential: credential).Result;
if (result == null) throw new InvalidOperationException("Failed to obtain the JWT token");
_authnToken = result.AccessToken;
}
public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null) throw new ArgumentNullException(nameof(request));
if (_authnToken == null) throw new InvalidOperationException("Token provider cannot be null");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authnToken);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
await base.ProcessHttpRequestAsync(request, cancellationToken);
}
}
class Program
{
static void Main(string[] args)
{
var client = new ResourceManagementClient(new CustomLoginCredentials())
{
SubscriptionId = YOUR_SUBSCRIPTION_ID"
};
var result = client.ResourceGroups.ExportTemplate("YOUR_RESGROUP",
new ExportTemplateRequest {
Options = "SkipAllParameterization",
Resources = new List<string> { "/subscriptions/YOUR_SUBSCRIPTION_ID/resourceGroups/YOUR_RESGROUP/providers/Microsoft.Storage/storageAccounts/datalakestg1" } });
Console.WriteLine(result.Template);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment