Search code examples
azureterraformgithub-actionsterraform-provider-azure

Authenticating to Azure using Managed Identity with Terraform


I am attempting to follow these steps to authenticate to the Terraform Azure Provider using managed identity in a GitHub Action: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/managed_service_identity

My config is as follows:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.105.0"
    }
  }
  backend "azurerm" {}
}

provider "azurerm" {
  features {}
}

My script in my GHA:

export ARM_USE_MSI=true
export ARM_SUBSCRIPTION_ID=${{ inputs.azure_subscription_id }}
export ARM_TENANT_ID=${{ inputs.azure_tenant_id }}
terraform init -reconfigure -backend-config="backends/${{ inputs.env }}.conf"
terraform plan -var-file="${{ inputs.env }}.tfvars" -var='hosts=${sites}'

And I'm getting the following error message:

Error: Failed to get existing workspaces: Error retrieving keys for Storage Account "<storage account name>": azure.BearerAuthorizer#WithAuthorization: Failed to refresh the Token for request to https://management.azure.com/subscriptions/<subscriptionid>/resourceGroups/<resource group>/providers/Microsoft.Storage/storageAccounts/<storage account name>/listKeys?api-version=2021-01-01: StatusCode=400 -- Original Error: adal: Refresh request failed. Status Code = '400'. Response body: {"error":"invalid_request","error_description":"Identity not found"} Endpoint http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F

Any ideas what I am missing? The storage account it's trying to access is my backend storage account.


Solution

  • The solution in my case was to use a Service Principal w/ Client Secret: https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/guides/service_principal_client_secret.

    I was attempting to use the Managed Service Identity, which is consistent with how I was using Bicep. Bicep never required me to use the Client Secret.