Azure GCC High环境Terraform init报错:SubscriptionNotFound
问题场景
我在Azure GCC High环境中使用Az CLI执行terraform init时遇到错误,想要将tfstate存储在订阅A,同时把资源部署到同租户的订阅B。这套配置在商用Azure环境中可以正常运行,但在GCC High环境中报错。
错误信息
Initializing the backend... ╷ │ Error: Failed to get existing
workspaces: Error retrieving keys for Storage Account
"storageaccount": storage.AccountsClient#ListKeys: Failure responding
to request: StatusCode=404 -- Original Error: autorest/azure: Service
returned an error. Status=404 Code="SubscriptionNotFound" Message="The
subscription '' could not be found."
已执行操作
我已经清理了.azure文件夹,执行az cloud set --name AzureUSGovernment切换到美国政府云,再执行az login登录。登录完成后,输出显示我拥有管理员权限的所有订阅(包括目标的两个订阅)均可见且已启用。
配置代码
terraform { required_providers { azurerm = { source = "hashicorp/azurerm" version = "~> 3.27.0" } } backend "azurerm" { subscription_id = "<Subscription A GUID>" tenant_id = "<Tenant GUID>" resource_group_name = "rg-demo" storage_account_name = "storagename" container_name = "tfstate" key = "env/state.tfstate" } } provider "azurerm" { features {} subscription_id = <Subscription B GUID> tenant_id = <Tenant GUID> }
排查与解决步骤
显式指定政府云环境端点
GCC High环境的服务端点与商用Azure存在差异,即使执行了云环境切换,也需要在backend配置中明确指定环境类型,避免Terraform误调用商用端点:backend "azurerm" { subscription_id = "<Subscription A GUID>" tenant_id = "<Tenant GUID>" resource_group_name = "rg-demo" storage_account_name = "storagename" container_name = "tfstate" key = "env/state.tfstate" environment = "usgovernment" # 强制指定美国政府云环境 }修正Provider订阅ID的语法错误
注意原配置中provider块的subscription_id未加双引号,这会导致Terraform解析异常,即使商用环境兼容,GCC High环境对语法要求更严格,必须添加双引号:provider "azurerm" { features {} subscription_id = "<Subscription B GUID>" tenant_id = "<Tenant GUID>" }强制切换到存储tfstate的订阅上下文
登录后可见所有订阅,但Terraform初始化时可能未自动切换到订阅A,需手动指定:az account set --subscription "<Subscription A GUID>"初始化完成后,Terraform会根据provider配置自动切换到订阅B执行资源部署。
验证存储账户的RBAC权限
确认当前登录账号对订阅A中的存储账户拥有Storage Account Key Operator Service Role或更高权限,避免因权限不足导致的404:az role assignment list --assignee $(az account show --query user.name -o tsv) --scope "/subscriptions/<Subscription A GUID>/resourceGroups/rg-demo/providers/Microsoft.Storage/storageAccounts/storagename"升级Azurerm Provider版本
3.27.0版本对GCC High环境的支持可能存在bug,建议升级到兼容的新版本(如~> 3.70.0),确保版本已适配美国政府云特性:required_providers { azurerm = { source = "hashicorp/azurerm" version = "~> 3.70.0" } }
内容的提问来源于stack exchange,提问作者BradSherwin

