You need to enable JavaScript to run this app. 如何在脚本中使用Terraform Output将VM私有IP存储到实例本地
优惠活动
大模型
产品
解决方案
定价
更多

如何在脚本中使用Terraform Output将VM私有IP存储到实例本地

解决方案

错误原因

你当前的写法无法生效是因为autoo.sh是上传到云服务器内部执行的Shell脚本,运行环境中不存在Terraform的资源属性变量google_compute_instance.default.network_interface.0.network_ip,因此无法读取到对应值。

可行实现方案

方案1:Terraform直接传参给脚本

这是成本最低的修改方案,只需调整两处配置即可:

  1. 修改autoo.sh脚本,接收外部传入的私有IP参数:
#!/bin/bash
# 建议写绝对路径,避免找不到文件
touch /root/myip.txt
private_ip=$1
echo "$private_ip" >> /root/myip.txt
  1. 修改Terraform的remote-exec配置,将Terraform侧读取到的私有IP作为参数传递给脚本:
provisioner "remote-exec" {
  inline = [
    "sudo chmod +x /tmp/autoo.sh",
    "sudo bash /tmp/autoo.sh ${google_compute_instance.default.network_interface.0.network_ip}",
  ]
  connection {
      host = google_compute_address.static.address
      type = "ssh"
      user = var.user
      private_key = file(var.privatekeypath)
  }
}

方案2:模板预渲染脚本

如果脚本逻辑复杂,推荐用Terraform的模板渲染功能,把私有IP直接写入脚本后再上传到服务器:

  1. 将原autoo.sh重命名为autoo.sh.tpl作为模板文件,内容修改为:
#!/bin/bash
touch /root/myip.txt
private_ip="${private_ip}"
echo "$private_ip" >> /root/myip.txt
  1. 修改Terraform的file provisioner配置,渲染模板后上传:
provisioner "file" {
  content = templatefile("${path.module}/autoo.sh.tpl", {
    private_ip = google_compute_instance.default.network_interface.0.network_ip
  })
  destination = "/tmp/autoo.sh"
  connection {
      host = google_compute_address.static.address
      type = "ssh"
      user = var.user
      private_key = file(var.privatekeypath)
  }
}

remote-exec配置无需修改,直接执行脚本即可生效。

方案3:实例内部查询元数据获取IP

GCP实例内部可以直接访问元数据接口获取自身私有IP,无需依赖Terraform传值,适合不想修改Terraform传参逻辑的场景,直接修改autoo.sh内容即可:

#!/bin/bash
touch /root/myip.txt
# 调用GCP元数据接口获取私有IP
private_ip=$(curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/ip)
echo "$private_ip" >> /root/myip.txt

注意事项

  • 脚本中写入文件建议使用绝对路径,避免因执行用户的工作目录不同导致找不到生成的myip.txt文件
  • 如果需要普通用户也能读取生成的IP文件,可调整文件路径为/home/你的用户名/myip.txt,或者执行chmod修改文件权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 07:15:03