Michelle Welcks
Michelle Welcks

Reputation: 3894

Terraform fails using an Azure service principal for authentication

Problem

Terraform gives the following error when trying to use terraform plan or terraform apply after create a service principal in Azure:

provider.azurerm: No valid (unexpired) Azure CLI Auth Tokens found. Please run az login.

Steps to Reproduce

Create a service principal in Azure via az ad sp create-for-rbac.

Add the service principal configuration as a provider block to your .tf file:

provider "azurerm" {
  alias = "tf_bootstrap"
  client_id = "55708466-3686-xxxx-xxxx-xxxxxxxxxxxx"
  client_secret = "88352837-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  tenant_id = "129a861e-a703-xxxx-xxxx-xxxxxxxxxxxx"
  subscription_id = "c2e9d518-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

resource "azurerm_resource_group" "dev" {
  name     = "dev-rg"
  location = "East US"
}

Attempt to run terraform plan.

Upvotes: 0

Views: 901

Answers (1)

Michelle Welcks
Michelle Welcks

Reputation: 3894

If using the alias key in a provider block, as shown in the question, a provider key must be specified in each data or resource blocks.

For example:

// When a provider alias has been defined.
resource "azurerm_resource_group" "dev" {
  provider = "azurerm.tf_bootstrap"
  name     = "dev-rg"
  location = "East US"
}

If you miss a provider for one of your resources or data blocks, authentication fails on that block.


Note however that is also valid to not specify an alias key in the original provider block. In that case, it is no longer necessary to specify a provider key in every resource and data block; the provider key can be omitted.

// When a provider alias has not been defined.
resource "azurerm_resource_group" "dev" {
  name     = "dev-rg"
  location = "East US"
}

Upvotes: 1

Related Questions