Terraform templatefile 条件语句生成ansible inventory文件

Terraform templatefile conditional statement to generate ansible inventory file

// 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 清单文件。只有当我将 boolean true 参数传递给我的“launch_zk”变量时,它才应该包括 zookeeper 的 IP 和 DNS,否则它不应该打印任何东西。在这里,我无法在我的输出文件和 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.

docs 所述,您的条件必须具有 一致的类型:

The two result values may be of any type, but they must both be of the same type so that Terraform can determine what type the whole conditional expression will return without knowing the condition value.

在你的情况下你 return 一个列表,和字符串:

#                              ? 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 : []

此更改可能需要进一步更改您的代码以解决空列表问题