Skip to content

Instantly share code, notes, and snippets.

@csiebler
Created May 7, 2019 06:35
Show Gist options
  • Save csiebler/289cd2c5d7eed41e2832f5fdd1710d76 to your computer and use it in GitHub Desktop.
Save csiebler/289cd2c5d7eed41e2832f5fdd1710d76 to your computer and use it in GitHub Desktop.
Provisioning Azure resources using Managed Identity (w/local fallback) and Azure Fluent SDK
System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Rest;
namespace APIMSITest.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
AzureServiceTokenProvider tokenProvider = new AzureServiceTokenProvider();
var managementToken = await tokenProvider.GetAccessTokenAsync("https://management.azure.com/").ConfigureAwait(false);
var tenantId = "xxxxx-xxxx-xxxx-xxxxxx";
var azureCredentials = new AzureCredentials(new TokenCredentials(managementToken), null, tenantId, AzureEnvironment.AzureGlobalCloud);
var azure = Azure
.Configure()
.Authenticate(azureCredentials)
.WithDefaultSubscription();
var rgs = new List<string>();
var resourceGroups = await azure.ResourceGroups.ListAsync();
foreach (var r in resourceGroups)
{
Console.WriteLine($"Resource group {r.Name}");
rgs.Add(r.Name);
}
return rgs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment