Create Inventory File from Terraform when for_each is used

Viewed 693

I have the following structure:

Terraform Azure Pipeline Structure

The PreProd > Variables.tf has:

variable "vms" {

  default = [
    {
      "hostname" : "Monitor01",
      "size" : "Standard_D2as_v4"
      "managed_disk_type" : "Premium_LRS"
      "extra_tag" : {
        "name" : "monitoring1",
        "env" : "dev",
        "role" : "test1"
      }
    },
    {
      "hostname" : "Monitor02",
      "size" : "Standard_D2as_v4"
      "managed_disk_type" : "Premium_LRS"
      "extra_tag" : {
        "name" : "monitoring2",
        "env" : "dev",
        "role" : "test2"
      }
    },

The Modules > main.tf has:

# Create public IP's
resource "azurerm_public_ip" "publicip" {
  for_each = { for vm in var.vms : vm.hostname => vm }

  name                = "${each.value.hostname}-PublicIP"
  location            = var.vm_location
  resource_group_name = var.vm_resource_group
  allocation_method   = "Static"
}

# Create network interface for Public IP's
resource "azurerm_network_interface" "publicnic" {
  for_each = { for vm in var.vms : vm.hostname => vm }
  name                = "${each.value.hostname}-NIC"
  location            = var.network_location
  resource_group_name = var.vm_resource_group
  ip_configuration {
    name                          = "monitoringConfg"
    subnet_id                     = data.azurerm_subnet.vm_subnet.id
    private_ip_address_allocation = "dynamic"
    public_ip_address_id          = azurerm_public_ip.publicip[each.key].id
  }
  tags = each.value.extra_tag
}

# Create Linux virtual machines
resource "azurerm_virtual_machine" "vm" {
  for_each = { for vm in var.vms : vm.hostname => vm }

  name                             = each.value.hostname
  location                         = var.vm_location
  resource_group_name              = var.vm_resource_group
  network_interface_ids            = [azurerm_network_interface.nic[each.key].id]
  vm_size                          = each.value.size
  delete_data_disks_on_termination = true
  delete_os_disk_on_termination    = true

I would like to create an inventory file for all the VM's and their public and private Ip's.

The Modules > Outputs.tf has:

output "vm_names" {
  description = "Name of VMs"
  value = [for k, vm in azurerm_virtual_machine.vm: vm.name]
}

data  "template_file" "inventory" {
  template = "${file("${path.module}/inventory.tmpl")}"
  vars = {
         #k8s_master_name = azurerm_network_security_group.toolservernsg.id
         k8s_master_name = [for k, p in azurerm_virtual_machine.vm: p.name]
     }
 }

 resource "local_file" "save_inventory" {
   content  = "${data.template_file.inventory.rendered}"
   filename = "./myhosts.cfg"
 }

The Modules > inventory.tmpl file has:

[servers]
${k8s_master_name}

I am struggling to get a myhosts.cfg file created with the following structure:

[servers]
Monitor01 privateip="x.x.x.x" publicip="x.x.x.x."
Monitor02 privateip="x.x.x.x" publicip="x.x.x.x."

[nsg]

I get the following error when I do a terraform apply:

Incorrect attribute value

when I do a terraform output, I get the following:

Terraform output : no outputs found

I have read through a lot of forums and tried all these output variations but I cant get the desired result:

output "vm_name" {
  description = "Name of VMs"
  value       = values(azurerm_virtual_machine.vm)[*].name
}

output "vm_name2" {
  description = "Name of VMs as a map"
  value = {for k, vm in azurerm_virtual_machine.vm : k => vm.name}
}

output "vm_name3" {
  description = "Name of VMs as a map"
  value = azurerm_virtual_machine.vm[*].name
}

output "vm_names" {
  description = "Name of VMs as a map"
  value = [for p in azurerm_virtual_machine.vm:p.name]
}
2 Answers

template_file can only accept string, but you are passing a list of values to it. So it fails.

You can try with jsonencode:

data  "template_file" "inventory" {
  template = "${file("${path.module}/inventory.tmpl")}"
  vars = {
         k8s_master_name = jsonencode([for k, p in azurerm_virtual_machine.vm: p.name])
     }
 }

Alternatively, you can look at templatefile which can accept list of values, as opposed to template_file.

Thanks Marcin, I ended up using templatefile. For others looking for an answer, this is what I did.

Outputs.tf file:

### The Ansible inventory file
resource "local_file" "AnsibleInventory" {
 content = templatefile("${path.module}/inventory.tmpl",
   {
     vm-names                   = [for k, p in azurerm_virtual_machine.vm: p.name],
     private-ip                 = [for k, p in azurerm_network_interface.nic: p.private_ip_address],
     publicvm-names             = [for k, p in azurerm_virtual_machine.publicvm: p.name],
     publicvm-private-ip        = [for k, p in azurerm_network_interface.publicnic: p.private_ip_address],
     public-ip                  = [for k, p in azurerm_public_ip.publicip: p.ip_address],
     public-dns                 = [for k, p in azurerm_public_ip.publicip: p.fqdn],
   }
 )
 filename = "hosts.cfg"
}

Inventory.tmpl file:

[servers]
%{ for index, vms in vm-names ~}
${vms} ansible_host=${private-ip[index]}
%{ endfor ~}
%{ for index, vms in publicvm-names ~}
${vms} ansible_host=${publicvm-private-ip[index]} public_ip=${public-ip[index]} 
%{ endfor ~}

This ended up giving me a hosts.cfg file:

[servers]
Monitor01 ansible_host=x.x.x.x
Monitor02 ansible_host=x.x.x.x
MonitorPublic01 ansible_host=x.x.x.x public_ip=x.x.x.x
MonitorPublic02 ansible_host=x.x.x.x public_ip=x.x.x.x
 
Related