Search code examples
terraformterraform-template-file

how to append a index number in terraform template file


I'm preparing ansible inventory file from terraform using terraform template.In that i wan to create a inventory file content as like below

slave-01 ansible_host=x.x.x.x
slave-02 ansible_host=x.x.x.x

So here i'm unable to append the numbers 01,02...etc based on how many ip addresses are there for that resource

My template file what i;m trying is as below

%{ for index,ip in test_slaves ~}
slave-[index] ansible_host=${ip}
%{ endfor ~}

My resource file is

resource "local_file" "hosts_cfg" {
  content = templatefile("${path.module}/templates/hosts.tpl",
    {
      test_slaves  = aws_instance.test-slaves.*.public_ip
    }
  )
  filename = "${path.module}/hosts.cfg"
}

Please guide me how i can handle this?


Solution

  • As you've seen for the ip value, you can use template interpolation to insert dynamic strings into your template output.

    However, in your case you have a number and you want it to be formatted in a different way than Terraform would default to when converting a number to a string: you want it to be zero-padded to always have two decimal (I assume!) digits.

    For custom number formatting Terraform has the format function, which allows you to use a format string to describe to Terraform how to present your number. For a decimal representation of a number we can use %d ("d" for decimal) and for zero-padding to two digits we can use the 02 prefix, where the 0 means zero-padding (rather than space-padding) and the 2 means two digits.

    Putting that all together we can include a call to format as part of the template by writing that call inside an interpolation sequence:

    %{ for index, ip in test_slaves ~}
    ${format("slave-%02d", index + 1)} ansible_host=${ip}
    %{ endfor ~}
    

    I included the slave- prefix as part of the format string here, which illustrates that the format function will just pass through any characters that are not formatting "verbs" (starting with %) literally. You could alternatively write that prefix outside of the interpolation sequence, with the same effect.