Terraform plan执行报错:资源引用无效,请求协助排查
问题排查与解决
错误根源
你碰到的Invalid reference错误,并非实例名称引用错误,而是Terraform会自动解析local-exec命令块里所有${}格式的内容——代码里的${zone}是Shell层面的变量,但Terraform会把它当成自身的资源/变量引用,因找不到对应定义而抛出错误。
修复方案
将Shell变量${zone}转义为\${zone},让Terraform跳过解析,直接把这个变量传递给Shell执行。修改后的local-exec代码片段如下:
provisioner "local-exec" { when = create command = <<-EOT zone=$(gcloud compute instances describe ${google_compute_instance_from_template.compute_instance[count.index].name} --project=${local.project_id} --format="value(zone)") && \ while gcloud compute instances describe ${google_compute_instance_from_template.compute_instance[count.index].name} --project=${local.project_id} --flatten="metadata[]" | grep -q am_i_healthy ; do sleep 5 done gcloud compute instances describe ${google_compute_instance_from_template.compute_instance[count.index].name} --project=${local.project_id} --zone=\${zone} --flatten="metadata[]" >> ${self.triggers.health_report} EOT on_failure = fail environment = { TF_LOG = "DEBUG" } }
额外验证项
- 确认
google_compute_instance_from_template.compute_instance是正确的资源引用,即你定义的google_compute_instance_from_template资源名称确实为compute_instance。 - 确保
local.project_id变量已正确定义且能被当前资源访问。
内容的提问来源于stack exchange,提问作者Priyanka Singh
相关产品推荐
相关产品推荐

