Terraform azapi provider "ChainedTokenCredential authentication failed"

314 Views Asked by At

I am trying to create a Virtual Machine Image using the Terraform azapi provider. Within the same configuration I'm also using Azurerm, which works fine.

This is how I set up my providers:

terraform {
  required_version = "~>1.4.0"
  backend "azurerm" {}
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.64.0"
    }
    # Additional providers must be added below
    azapi = {
      source  = "Azure/azapi"
      version = "=1.10.0"
    }
  }
}

provider "azurerm" {
  subscription_id = <Subscription ID>

  features {}
  skip_provider_registration = "true"
}

provider "azapi" {
  subscription_id   = <Subscription ID>
  use_cli           = true
}

This is the resource that I am trying to deploy:

resource "azapi_resource" "<Reference-Name>" {
  type      = "Microsoft.VirtualMachineImages/imageTemplates@2022-02-14"
  name      = "<Resource-Name>"
  location  = "westeurope"
  parent_id = <Resource Group id>
  tags      = var.tags
  identity {
    type         = "UserAssigned"
    identity_ids = [<Managed identity id>]
  }
  body = jsonencode({
    properties = {
      buildTimeoutInMinutes = 0
      customize = [
        {
          name        = <script-name>
          type        = "PowerShell"
          runAsSystem = true
          runElevated = true
          scriptUri   = <script URL>
        }
      ]
      distribute = [
        {
          artifactTags      = {}
          runOutputName     = <output-name>
          type              = "SharedImage"
          excludeFromLatest = true
          galleryImageId    = <gallery-id>
          replicationRegions = [
            "westeurope"
          ]
          storageAccountType = "Blob"
        }
      ]
      validate = {
        continueDistributeOnFailure = true
      }
      source = {
        type      = "PlatformImage"
        publisher = "MicrosoftWindowsDesktop"
        offer     = "Windows-10"
        sku       = "22h2-avd"
        version   = "latest"
      }
      stagingResourceGroup = <staging RG name>
      vmProfile = {
        osDiskSizeGB = 64
        vmSize = "Standard_B2ms"
        vnetConfig = {
          subnetId = <subnet id>
        }
      }
    }
  })
}

I am using the Azure CLI for authentication. But when I try to apply this I get the following error:

│ Error: checking for presence of existing Resource: (ResourceId "/subscriptions/<Subscription ID>/resourceGroups/<RG-name> /providers/Microsoft.VirtualMachineImages/imageTemplates/<Resource-name>" / Api Version "2022-02-14"): ChainedTokenCredential authentication failed
│ GET http://169.254.169.254/metadata/identity/oauth2/token
│ --------------------------------------------------------------------------------
│ RESPONSE 403 connecting to 169.254.169.254:80: connecting to 169.254.169.254:80: dial tcp 169.254.169.254:80: connectex: A socket operation was attempted to an unreachable network.
│ ---------------------------
│ connecting to 169.254.169.254:80: connecting to 169.254.169.254:80: dial tcp 169.254.169.254:80: connectex: A socket operation was attempted to an unreachable network.
│ --------------------------------------------------------------------------------
│ 
│ 
│   with azapi_resource.avd_image,
│   on main.tf line 80, in resource "azapi_resource" "<Resource-name>":
│   80: resource "azapi_resource" "<Resource-name>" {

I couldn't find anything online that would explain why only azapi would fail but azurerm would not. I have also tried it for different resources with azapi, and that results in the same error. I have also tried connecting to different networks. What could be my mistake here?

1

There are 1 best solutions below

3
Vinay B On

I tried to create a Virtual Machine Image using the Terraform azapi provider and I was able to provision the requirement successfully.

The error you are encountering, "ChainedTokenCredential authentication failed", typically indicates an issue with Azure CLI authentication or Managed Identity configuration.

Since you're using Azure CLI for authentication (use_cli = true in the azapi provider configuration), ensure that you are logged in with the Azure CLI and have the correct permissions

Run az login to authenticate your Azure CLI session, and verify with az account show that you are logged in to the correct account with necessary permissions.

For reference you can use this path to re-install the Azure CLI if youre using in local.

enter image description here

My demo terraform configuration:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "= 3.84.0"
    }
    azapi = {
      source  = "Azure/azapi"
      version = "= 1.10.0"
    }
  }
}

provider "azurerm" {
  features {}
  subscription_id = "your subscription ID"
  skip_provider_registration = "true"
}


provider "azapi" {
  subscription_id = "Your subscription ID"
  use_cli         = true
}

resource "azurerm_resource_group" "example_rg" {
  name     = "demorg-vk"
  location = "east us"
}

resource "azurerm_virtual_network" "example_vnet" {
  name                = "vkvnet"
  address_space       = ["10.0.0.0/16"]
  location            = azurerm_resource_group.example_rg.location
  resource_group_name = azurerm_resource_group.example_rg.name
}

resource "azurerm_subnet" "example_subnet" {
  name                 = "vksnet"
  resource_group_name  = azurerm_resource_group.example_rg.name
  virtual_network_name = azurerm_virtual_network.example_vnet.name
  address_prefixes     = ["10.0.1.0/24"]
}

resource "azurerm_user_assigned_identity" "example" {
  resource_group_name = azurerm_resource_group.example_rg.name
  location            = azurerm_resource_group.example_rg.location
  name                = "demovk-identity"
}

resource "azurerm_network_interface" "example_nic" {
  name                = "demovkNIC"
  location            = azurerm_resource_group.example_rg.location
  resource_group_name = azurerm_resource_group.example_rg.name

  ip_configuration {
    name                          = "internal"
    subnet_id                     = azurerm_subnet.example_subnet.id
    private_ip_address_allocation = "Dynamic"
  }
}

resource "azapi_resource" "vm" {
  type      = "Microsoft.Compute/virtualMachines@2022-03-01"
  name      = "demoVM"
  location  = "east us"
  parent_id = azurerm_resource_group.example_rg.id
  depends_on = [azurerm_network_interface.example_nic]
  body = jsonencode({
    properties = {
      hardwareProfile = {
        vmSize = "Standard_B8ms"
      },
      storageProfile = {
        imageReference = {
          publisher = "Canonical"
          offer     = "UbuntuServer"
          sku       = "18.04-LTS"
          version   = "latest"
        },
        osDisk = {
          createOption = "FromImage"
          caching             = "ReadWrite"
          managedDisk = {
            storageAccountType = "Standard_LRS"
          }
           diskSizeGB          = 30 
        }
      },
      osProfile = {
        computerName  = "demovkVM"
        adminUsername = "adminuser"
        adminPassword = "YouPassword123!" // Replace with a secure password
      },
      networkProfile = {
        networkInterfaces = [
          {
            id = azurerm_network_interface.example_nic.id,
            properties = {
              primary = true
            }
          }
        ]
      },
      // Additional properties as required
    },
    identity = {
      type = "SystemAssigned"
    }
  })
}

Output:

enter image description here

enter image description here