gpt4 book ai didi

azure - 使用 Terraform 创建 Ansible 库存

转载 作者:行者123 更新时间:2023-12-02 08:19:01 26 4
gpt4 key购买 nike

我正在尝试使用 Terraform 中的 local_file 函数创建 Ansible 库存文件(我愿意接受以不同方式执行此操作的建议)

模块“vm”配置:

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 列表注入(inject)到本地文件中,同时还能够格式化文件中的其余文本?

最佳答案

如果您希望 Ansible list 从 INI 格式的文件静态获取,那么您基本上需要在 Terraform 中渲染模板以生成所需的输出。

模块/模板/inventory.tmpl:

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

@mdaniel 的替代建议:

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

模块/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
}

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

您还可以使用YAML or JSON inventory formats用于 Ansible 静态库存。有了这些,您就可以利用 yamldecodejsondecode Terraform 函数使 HCL2 数据结构转换变得更加容易。在这种情况下,对于更复杂的 list ,模板文件会变得更加干净。

关于azure - 使用 Terraform 创建 Ansible 库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70464397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com