首页 > 解决方案 > 如何在terraform中的变量后插入文件名?

问题描述

我正在构建一个自动部署多个应用程序的 tf 脚本。部署的一些云资源是虚拟机,部署后需要运行一些脚本。为了自动化这个任务,我声明了几个映射这些脚本的变量。

今天,它的工作方式类似于以下示例:

我在variables.tf文件中声明了几十个脚本变量

variable "path_script_backend" {
  type        = string
  description = "The path to the backend script"
  default = "/application/scripts/backend.sh"
}

然后,我使用该变量在实例上运行必要的脚本

应用程序.tf

# Connect to the instance via Terraform and remotely executes the install script using SSH

    provisioner "file" {
        source      = var.path_script_backend
        destination = "/tmp/backend.sh"
      }
    
      provisioner "remote-exec" {
        inline = [
          "sudo chmod +x /tmp/backend.sh",
          "sudo /tmp/backend.sh"
        ]
      }

一切正常,但我从操作团队收到的反馈是,他们需要很长时间才能在多个应用程序脚本中复制和粘贴这些文件路径,他们希望我只需使用一个变量来映射脚本所在的文件夹位于。

有了这个,我尝试了以下方法:

变量.tf

variable "folder_scripts" {
  type        = string
  description = "The path to the scripts folder"
  default = "/application/scripts"
}

然后,我使用文件夹变量 + 文件名在实例上运行必要的脚本

应用程序.tf

# Connect to the instance via Terraform and remotely executes the install script using SSH

    provisioner "file" {
        source      = var.folder_scripts"/backend.sh"
        destination = "/tmp/backend.sh"
      }

但上述方法不起作用,因为 terraform 不喜欢这种格式。我尝试了不同的组合和正则表达式来匹配文件,但无济于事。

关于我可以做些什么来解决它的任何想法?

提前谢谢

标签: terraformterraform-provider-gcp

解决方案


推荐阅读