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

如何从Terraform的null_resource中获取主机名并传入curl命令?

解决Azure虚拟机规模集主机名传递到curl命令的方法

要把从VMSS实例获取的主机名传入另一个null_resource的local-exec curl命令,核心是先捕获远程主机名并保存到Terraform状态中,再在后续资源里引用。以下是具体实现步骤:

1. 改造主机名获取逻辑,捕获输出并存储

原null_resource.get_hostname仅执行远程命令但未保留结果,我们改用local-exec直接通过SSH执行远程命令,将主机名写入本地临时文件,再通过triggers把主机名存入Terraform状态:

data "azurerm_virtual_machine_scale_set" "virtual_machine" {
  name                = var.vm_name
  resource_group_name = var.rg_name
}

resource "null_resource" "get_hostname" {
  count = var.instances

  provisioner "local-exec" {
    # 用sshpass+ssh直接执行远程hostname命令,结果写入本地文件
    command = <<EOT
      sshpass -p "${var.vm_password}" ssh -o StrictHostKeyChecking=no ${var.vm_username}@${data.azurerm_virtual_machine_scale_set.virtual_machine.instances[count.index].private_ip_address} "hostname -a" > ./hostname_${count.index}.txt
    EOT
  }

  # 将主机名存入triggers,供后续资源引用
  triggers = {
    hostname = trimspace(file("./hostname_${count.index}.txt"))
  }
}

2. 在curl命令中引用捕获的主机名

修改null_resource.add_dns_record,添加依赖确保主机名已获取,然后直接引用get_hostname的triggers.hostname字段:

resource "null_resource" "add_dns_record" {
  count = var.instances
  # 必须添加依赖,保证先完成主机名获取再执行curl
  depends_on = [null_resource.get_hostname]

  provisioner "local-exec" {
    command = <<EOT
      # 补全你的API地址,确保JSON格式正确
      curl -X POST -H "Content-Type: application/json" -d '{"_name": "${null_resource.get_hostname[count.index].triggers.hostname}"}' https://your-dns-api.example.com/records
    EOT
  }
}

注意事项

  • 需提前在执行Terraform的机器上安装sshpass(用于密码登录SSH),如果用SSH密钥认证,可以移除sshpass -p "${var.vm_password}"部分,改用-i /path/to/ssh-key。
  • StrictHostKeyChecking=no是为了避免首次SSH连接时的手动确认,生产环境建议改为StrictHostKeyChecking=accept-new更安全。
  • 确保curl命令的JSON格式正确,原示例中的命令存在语法错误,已修正为标准POST请求格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:44:52