使用Terraform创建可选清单 [英] Create Ansible inventory using Terraform

查看:29
本文介绍了使用Terraform创建可选清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Terraform中的LOCAL_FILE函数创建Ansible清单文件(我欢迎以不同的方式提供建议)

模块&Quot;VM&Quot;配置:

resource "azurerm_linux_virtual_machine" "vm" {
  for_each                        = { for edit in local.vm : edit.name => edit }
  name                            = each.value.name
  resource_group_name             = var.vm_rg
  location                        = var.vm_location
  size                            = each.value.size
  admin_username                  = var.vm_username
  admin_password                  = var.vm_password
  disable_password_authentication = false
  network_interface_ids           = [azurerm_network_interface.edit_seat_nic[each.key].id]
  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

output "vm_ips" {
  value = toset([
    for vm_ips in azurerm_linux_virtual_machine.vm : vm_ips.private_ip_address
  ])
}

当我使用上述配置运行Terraform plan时,我得到:

Changes to Outputs:
  + test = [
      + "10.1.0.4",
    ]

现在,在我的主tf中,我有如下LOCAL_FILE的配置:

resource "local_file" "ansible_inventory" {
  filename = "./ansible_inventory/ansible_inventory.ini"
  content = <<EOF
  [vm]
  ${module.vm.vm_ips}
EOF
}

这将返回以下错误:

Error: Invalid template interpolation value
on main.tf line 92, in resource "local_file" "ansible_inventory":
90:   content = <<EOF
91:   [vm]
92:   ${module.vm.vm_ips}
93: EOF
module.vm.vm_ips is set of string with 1 element
Cannot include the given value in a string template: string required.

有什么建议如何将输出中的IP列表注入到本地文件中,同时还能格式化文件中文本的睡觉?

推荐答案

如果您希望静态地从INI格式的文件获取可用的清单,则基本上需要以Terraform格式呈现模板以生成所需的输出。

module/templates/inventory.tmpl

[vm]
%{ for ip in ips ~}
${ip}
%{ endfor ~}

来自@mdaniel的替代建议:

[vm]
${join("
", ips)}

module/config.tf

resource "local_file" "ansible_inventory" {
  content = templatefile("${path.module}/templates/inventory.tmpl",
    { ips = module.vm.vm_ips }
  )

  filename        = "${path.module}/ansible_inventory/ansible_inventory.ini"
  file_permission = "0644"
}

不过还有几个额外的注意事项:

您可以将输出修改为导出属性的整个对象映射,如下所示:

output "vms" {
  value = azurerm_linux_virtual_machine.vm
}

然后您可以访问有关要填充到清单中的实例的更多信息。您的templatefile参数仍将是模块输出,但是模板中的for表达式看起来会有很大的不同,具体取决于您要添加的内容。

您也可以使用YAML or JSON inventory formatsFor Ansible静电库存。有了这些,您就可以利用yamldecodejsondecodeTerraform函数来简化HCL2数据结构转换。对于更复杂库存,模板文件在这种情况下会变得更加干净。

这篇关于使用Terraform创建可选清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆