Search code examples
terraformterraform-provider-azureansible-inventoryterraform-template-file

How to output a map in inventory file format using templatefile terraform function


I have a map variable given below local.inventory_map

{     
  "black" = [
    "xyz",  
  ]         
  "blue" = [
    "abc",  
    "xyz",  
  ]         
  "geen" = [  
    "abc",    
  ]        
  "red" = [   
    "abc",               
    "xyz",               
  ]           
  "yellow" = [           
    "xyz",               
  ]                      
}        

I am trying to use the terrafrom templatefile function to get the following text file, Expected output

[black]
xyz
[blue]
abc
xyz
[green]
abc
[red]
abc
xyz
[yellow]
xyz

I tried

resource "local_file" "host_file" {
  content = templatefile(".hosts.yaml.tftpl",
    {
     color_groups = local.inventory_map
    }
)

and then in the hosts.yaml.tftpl file, I just tried to output the map but got an error. Please help.

%{ for key, value in color_groups ~}
${key}:${value}
%{ endfor ~}

Solution

  • I was looking for this answer to get my desired output

    %{ for key, value in color_groups ~}
    [${ key }]
    %{ for v in value ~} 
    ${ v }
    %{ endfor ~}
    
    %{ endfor ~}