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

使用Terraform File Provisioner结合远程连接与模板文件时报错

问题诊断与修复方案

问题根源

File Provisioner的source参数要求传入本地文件的路径字符串,但你直接把templatefile函数渲染后的文件内容文本传给了它。Terraform会把这段带换行的文本当作本地文件路径去解析,自然触发"文件名/目录名语法不正确"的错误(法语提示对应这个含义)。

修复方案

有两种可行的解决方式,根据需求选择:

方式1:先渲染到本地临时文件,再上传

用local_file资源先把模板内容写入本地文件,再让File Provisioner引用这个文件的路径:

# 先将模板渲染为本地临时文件
resource "local_file" "rendered_script" {
  content  = templatefile("ansible/test.tfpl", { hello = "tada" })
  filename = "${path.module}/.rendered_test.sh" # 用隐藏文件避免目录混乱
}

resource "null_resource" "file_config" {
  # 确保本地文件渲染完成后再执行上传
  depends_on = [local_file.rendered_script]

  connection {
    type        = "ssh"
    user        = "XXX"
    host        = cloudplatform_postgre_cluster.cluster.host
    private_key = file(var.XXX)
  }

  provisioner "file" {
    source      = local_file.rendered_script.filename
    destination = "~/test.sh"
  }
}

方式2:直接用remote-exec写入远程文件

如果脚本内容不复杂,可跳过本地文件,用remote-exec通过SSH直接把模板内容写入远程机器的文件:

resource "null_resource" "file_config" {
  connection {
    type        = "ssh"
    user        = "XXX"
    host        = cloudplatform_postgre_cluster.cluster.host
    private_key = file(var.XXX)
  }

  provisioner "remote-exec" {
    inline = [
      "cat > ~/test.sh << 'EOF'", # 用EOF避免内容中的特殊字符被Shell解析
      templatefile("ansible/test.tfpl", { hello = "tada" }),
      "EOF",
      "chmod +x ~/test.sh" # 可选:给脚本添加执行权限
    ]
  }
}

补充说明

  • 你之前用local_file(推测你说的local_resource是该资源)调用模板没问题,是因为local_file的content参数本身就是接收文本内容,和File Provisioner的source参数要求完全不同。
  • 非模板文件能正常上传,是因为传入的是合法的本地文件路径,Terraform可以正确定位到文件。

内容的提问来源于stack exchange,提问作者Matthieu Raynaud de Fitte

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:30:59