所以我有两个完全相同的terraform模块......例外是有一个额外的远程执行步骤
模块A
provisioner "remote-exec" {
inline = [
"sudo chmod 777 -R ${var.setup_files_destination}",
"sudo ${var.setup_files_destination}/scripts/setup.sh ${var.setup_files_destination}",
]
connection {
user = "ec2-user"
private_key = "${file(var.private_key_location)}"
}
}
模块B - 差异是一个额外执行的脚本
provisioner "remote-exec" {
inline = [
"sudo chmod 777 -R ${var.setup_files_destination}",
"sudo ${var.setup_files_destination}/scripts/setup.sh ${var.setup_files_destination}",
]
connection {
user = "ec2-user"
private_key = "${file(var.private_key_location)}"
}
}
provisioner "remote-exec" {
inline = [
"sudo chmod 777 -R ${var.setup_files_destination}",
"${var.setup_files_destination}/scripts/setup_special.sh ${var.setup_files_destination}",
]
connection {
user = "ec2-user"
private_key = "${file(var.private_key_location)}"
}
}
除了此脚本差异外,模块具有完全相同的步骤。重复的terraform代码量大约为50行。
我想在Terraform中做什么
所以在Terraform方面,我想指定要作为列表执行的脚本,所以像
可变
variable "commands_to_execute" {
type = "list"
}
共同步骤
provisioner "remote-exec" {
inline = "[${var.commands_to_execute}]"
connection {
user = "ec2-user"
private_key = "${file(var.private_key_location)}"
}
}
感知使用共同步骤
module "instances" {
... rest of declaration...
commands_to_execute = [
"sudo chmod 777 -R ${var.setup_files_destination}",
"sudo ${var.setup_files_destination}/scripts/setup.sh ${var.setup_files_destination}",
]
}
当我运行时,我得到了
错误:模块'实例':未知变量引用:' setup_files_destination&#39 ;;用变量定义它'块
因此setup_files_destination
是模块内定义的变量,但不是使用模块的.tf
文件中定义的变量。它具有默认值,实际上是远程实例上shell脚本目录的位置。
我想将setup_files_destination
保留在模块中。所以我寻找的是一种推迟变量插值的方法,直到实际使用模块为止。 这可能是terraform吗?
答案 0 :(得分:1)
无法按照您尝试的方式推迟插值,您可以使用null_resource和计数来实现您要尝试的操作。这只会在模块初始化
中定义变量run_additional_setup = true
时运行脚本
resource "null_resource" "additional_setup" {
count = "${var.run_additional_setup == true ? 1 : 0}"
depends_on = ["aws_instance.my_instance"]
connection {
user = "ec2-user"
private_key = "${file(var.private_key_location)}"
}
provisioner "remote-exec" {
inline = [
"sudo chmod 777 -R ${var.setup_files_destination}",
"${var.setup_files_destination}/scripts/setup_special.sh ${var.setup_files_destination}",
]
}
}