You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Terraform创建Azure资源遇认证失败问题求助

问题分析

错误核心是Terraform默认尝试读取Azure CLI的本地会话凭证文件accessTokens.json,但该文件不存在。具体原因:

  • 未通过Azure CLI完成有效登录,未生成凭证文件
  • 已定义服务主体相关变量,但未在azurerm provider块中配置使用该认证方式,Terraform仍走默认的CLI认证流程
解决方法

方法1:Azure CLI认证(快速临时验证)

打开PowerShell/CMD执行以下命令完成登录:

az login
# 多订阅环境需指定目标订阅
az account set --subscription <你的订阅ID>

登录完成后重新运行terraform init和terraform apply,CLI会自动生成所需的accessTokens.json文件。

方法2:服务主体认证(生产/CI/CD推荐)

修改main.tf中的provider块,明确配置使用服务主体凭证,关联已定义的变量:

provider "azurerm" {
  features {}

  subscription_id = var.subscription_id
  tenant_id       = var.tenant_id
  client_id       = var.client_id
  client_secret   = var.client_secret
}

变量传入方式

  • 命令行参数(不推荐,明文暴露):
terraform apply -var "client_id=xxx" -var "client_secret=xxx" -var "tenant_id=xxx" -var "subscription_id=xxx"
  • terraform.tfvars文件(推荐):
    创建该文件并填入凭证:
client_id       = "你的客户端ID"
client_secret   = "你的客户端密钥"
tenant_id       = "你的租户ID"
subscription_id = "你的订阅ID"

重要:将terraform.tfvars加入.gitignore,禁止提交到版本控制系统。

额外注意事项

  • 由于你使用Terraform 0.15.4,需指定兼容的AzureRM Provider版本,避免兼容性问题:
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 2.99.0" # 该版本适配Terraform 0.15.x
    }
  }
}
  • 确认服务主体已被授予目标订阅的足够权限(如Contributor角色)
  • 使用服务主体认证时,无需再通过Azure CLI登录,Terraform会直接使用配置的凭证

内容的提问来源于stack exchange,提问作者Venki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:52:25