Problem
You are unable to authenticate the Terraform azurerm or azuread provider using an Azure managed identity when running plans in HCP Terraform. By default, HCP Terraform workspaces execute Terraform operations remotely on HashiCorp-managed infrastructure, which does not have access to your Azure environment's managed identities.
Cause
Managed identity authentication requires the process performing the authentication to be running on a supported Azure resource. HCP Terraform's default remote execution environment runs outside of your Azure infrastructure, so it cannot assume a managed identity that exists within it.
Prerequisites
To use managed identity for provider authentication, you must use HCP Terraform Agents.
- The agent must be deployed on one of the Azure resources that support managed identities.
- The Azure resource must meet the system requirements for running HCP Terraform agents.
Procedure
- Configure the workspace:Configure your HCP Terraform workspace to use the agent pool where your agent is registered.
-
Enable managed identity: Follow the Azure documentation to enable managed identity on the resource where the agent is running. You can also manage this with Terraform. Common examples include:
-
Azure Virtual Machine using the
azurerm_linux_virtual_machineidentityblock. -
Azure Container Instances using the
azurerm_container_groupidentityblock.
-
Azure Virtual Machine using the
-
Assign permissions: Ensure the managed identity has an appropriate role assignment for the subscription that Terraform will manage. See this example using
azurerm_role_assignment. -
Configure the provider: In your Terraform configuration, update the provider block to use managed identity. For the
azurermprovider, refer to the managed service identity guide. For theazureadprovider, the configuration is similar.The following example shows a configuration for the
azureadprovider.provider "azuread" { use_msi = true tenant_id = "72f988bf-xxxx-xxxx-xxxx-xxxxxxxxxxxx" }