// Terraform v0.14.9
# var.tf
variable "launch_zk" {
type = string
description = "Whether to launch zookeeper or not"
default = false
}
# main.tf
resource "aws_instance" "zk_ec2" {
count = var.launch_zk ? var.zk_instance_count : 0
...
}
# output.tf
output "zk_ips" {
description = "IPs of ZK instances"
value = {
for vm in aws_instance.zk_ec2 :
vm.tags.Name => vm.private_ip
}
}
resource "local_file" "AnsibleInventoryFile" {
content = templatefile("ansible_inventory.tpl",
{
zk-private-ip = var.zk_instance_count < 10 ? slice(aws_instance.zk_ec2.*.private_ip, 0, 3) : slice(aws_instance.zk_ec2.*.private_ip, 0, 5),
zk-private-dns = var.zk_instance_count < 10 ? slice(aws_instance.zk_ec2.*.private_dns, 0, 3) : slice(aws_instance.zk_ec2.*.private_dns, 0, 5),
}
)
filename = "ansible_inventory"
}
# ansible_inventory.tpl
[zk_servers]
%{ for index, dns in zk-private-dns ~}
${zk-private-ip[index]} server_name=${dns}
%{ endfor ~}
这就是我正在使用的,现在我想有条件地生成输出文件,包括ansible库存文件。它应该包括zookeeper的IP和DNS,只有当我将布尔true参数传递给我的"时;launch_zk";变量,否则不应打印任何内容。在这里,我无法在我的输出文件和ansible模板tpl文件中执行条件语句。有人能告诉我如何让它工作吗?
在这里,我将不得不使用这样的多个条件语句,但我在下面得到了错误
resource "local_file" "AnsibleInventoryFile" {
content = templatefile("ansible_inventory.tpl",
{
zk-private-ip = var.launch_zk ? var.zk_instance_count < 10 ? slice(aws_instance.zk_ec2.*.private_ip, 0, 3) : slice(aws_instance.zk_ec2.*.private_ip, 0, 5) : "",
zk-private-dns = var.launch ? var.zk_instance_count < 10 ? slice(aws_instance.zk_ec2.*.private_dns, 0, 3) : slice(aws_instance.zk_ec2.*.private_dns, 0, 5) : "",
}
)
filename = "ansible_inventory"
}
# Error
Error: Inconsistent conditional result types
on output.tf line 67, in resource "local_file" "AnsibleInventoryFile":
67: zk-private-dns = var.launch_zk ? aws_instance.zk_ec2.*.private_dns : "",
|----------------
| aws_instance.zk_ec2 is empty tuple
| var.launch_zk is "false"
The true and false result expressions must have consistent types. The given
expressions are tuple and string, respectively.
正如文档所解释的,您的条件必须具有一致类型:
这两个结果值可以是任何类型,但它们必须都是相同的类型,这样Terraform就可以在不知道条件值的情况下确定整个条件表达式将返回的类型。
在您的情况下,您返回一个列表和字符串:
# ? list : string
zk-private-dns = var.launch_zk ? aws_instance.zk_ec2.*.private_dns : ""
确保类型一致的最简单方法是使用空列表:
zk-private-dns = var.launch_zk ? aws_instance.zk_ec2.*.private_dns : []
此更改可能需要对代码进行进一步更改,以说明空列表