Terraform部署GCP托管实例组遇属性不存在报错求助
问题解决:Terraform引用remote_state输出触发"Unsupported attribute"错误
问题场景
我用以下Terraform代码在GCP部署托管实例组,通过data.terraform_remote_state引用现有基础架构资源的数据时,出现了属性不存在的错误:
resource "google_compute_instance_template" "this" { name_prefix = var.mig.instance_template_name_prefix region = var.region machine_type = var.mig.machine_type disk { source_image = var.mig.source_image } network_interface { subnetwork = data.terraform_remote_state.foundation.outputs.subnetwork_self_links["iowa"] access_config { // Ephemeral public IP } } metadata_startup_script = file("startup.sh") tags = [ "allow-iap", "allow-health-check" ] service_account { email = data.terraform_remote_state.foundation.outputs.service_account_email scopes = ["cloud-platform"] } lifecycle { create_before_destroy = true } } resource "google_compute_region_instance_group_manager" "this" { name = var.mig.mig_name region = var.region base_instance_name = var.mig.mig_base_instance_name target_size = var.mig.target_size version { instance_template = google_compute_instance_template.this.id } named_port { name = "http" port = 80 } update_policy { type = "PROACTIVE" minimal_action = "REPLACE" max_surge_fixed = 3 } }
错误信息
Plan: 1 to add, 0 to change, 0 to destroy. ╷ │ Error: Unsupported attribute │ │ on mig.tf line 12, in resource "google_compute_instance_template" "this": │ 12: subnetwork = data.terraform_remote_state.foundation.outputs.subnetwork_self_links["iowa"] │ ├──────────────── │ │ data.terraform_remote_state.foundation.outputs is object with no attributes │ │ This object does not have an attribute named "subnetwork_self_links". ╵ ╷ │ Error: Unsupported attribute │ │ on mig.tf line 25, in resource "google_compute_instance_template" "this": │ 25: email = data.terraform_remote_state.foundation.outputs.service_account_email │ ├──────────────── │ │ data.terraform_remote_state.foundation.outputs is object with no attributes │ │ This object does not have an attribute named "service_account_email".
解决建议
核对remote_state数据源配置
确认data "terraform_remote_state" "foundation"的配置是否正确指向了存储基础架构状态的后端(比如GCS桶、S3等)。若后端路径、桶名或工作区有误,会导致读取不到正确的输出值。确认基础架构模块的输出定义
生成foundation状态的Terraform代码必须明确定义对应输出,否则remote_state无法读取。在基础架构模块的outputs.tf中添加以下内容(根据实际资源调整value):output "subnetwork_self_links" { type = map(string) description = "子网的自链接" value = google_compute_subnetwork.your_subnet_resource.*.self_link } output "service_account_email" { type = string description = "服务账号邮箱" value = google_service_account.your_sa_resource.email }刷新状态数据
执行terraform refresh或重新应用基础架构模块,确保状态文件已更新并包含最新的输出值。检查输出名称拼写
确保代码中引用的subnetwork_self_links和service_account_email与基础架构模块输出的名称完全一致,大小写、下划线都不能出错。
内容的提问来源于stack exchange,提问作者Nani
相关产品推荐
相关产品推荐

