← Tech blog

Create a user-assigned Managed Identity

AzureAzure SDKManaged Identity

Previous blog post in the series: Introduction to Managed Identities

Posts in this series:

  • Introduction to Managed Identities
  • Create a user-assigned Managed Identity (this post)
  • Using Managed Identity with Azure SQL (coming soon)
  • Machine to Machine authentication (coming soon)

With the new Azure SDK Management Libraries I have had the requirement to create a user-assgined Identity. Unfortunately there is no easy way in the new SDK to do so. So I created my own little helper method.

Nuget Packages

Code

async Task<UserAssignedIdentity> CreateOrUpdateUserAssignedIdentity(string identityName, string resourceGroup)
{
    var armClient = new Azure.ResourceManager.ArmClient(new AzureCliCredential());
    var sub = await armClient.GetDefaultSubscriptionAsync();
    var rg = (await sub.GetResourceGroups().GetAsync(resourceGroup)).Value;
    var umi = new GenericResourceData(AzureLocation.WestEurope);
    var umiId = rg.Id.AppendProviderResource("Microsoft.ManagedIdentity", "userAssignedIdentities",
        identityName);
    var res = await armClient.GetGenericResources().CreateOrUpdateAsync(Azure.WaitUntil.Completed, umiId, umi);
    var userAssignedIdentity =
        res.Value.Data.Properties.ToObjectFromJson<UserAssignedIdentity>(new JsonSerializerOptions()
            { PropertyNameCaseInsensitive = true });
    return userAssignedIdentity;
}
record UserAssignedIdentity(string PrincipalId, string ClientId, string TenantId);