Azure Azure - Terraform templates

Managed Identity

Last updated: May 18, 2025
In this Terraform code, we create an Azure User Assigned Managed Identity using the azurerm_user_assigned_identity resource. Managed identities provide an automatically managed identity in Azure Active Directory for applications to use when connecting to resources that support Azure AD authentication, eliminating the need for credentials in code.

Following Azure best practices, user-assigned managed identities are preferred when you want to share the same identity across multiple resources or need to control the lifecycle of the identity independently. This approach enhances security by avoiding hard-coded credentials and improves reliability by leveraging Azure's managed identity infrastructure.

You can use this code to create a new managed identity:
resource "azurerm_user_assigned_identity" "managed_identity" {
  name                = "${local.resource_prefix_short}-mi"
  resource_group_name = azurerm_resource_group.rg.name
  location            = local.location
  tags                = local.tags
}

This code only creates the managed identity, but doesn't assign it any roles. To assign a role, you can use the following example which assigns contributor role on resource group "rg" to the identity:
resource "azurerm_role_assignment" "managed_identity_contributor" {
  scope                = azurerm_resource_group.rg.id
  role_definition_name = "Contributor"
  principal_id         = azurerm_user_assigned_identity.managed_identity.principal_id
}