Search code examples
amazon-web-servicesterraformterraform-provider-awsterraform-template-file

Iterate through count of resources with terraform templatefile & save individual file per iteration


Iterate through count of resources with terraform templatefile & save individual file per iteration.

Hi, I am trying to move from using template_file to using templatefile in terraform.

Terraform needs to loop through a count of nodes, then create a individual file for each node.

I use count inside my terraform data and resource for template_file but this does not work in locals. As count is only used in resources. I believe I need to use a for loop but not quite sure how to implement it.

Here are examples of the template_file method. These work perfectly but I would like to convert them to use templatefile

    #Template Data
    data "template_file" "ansible_inventory" {
      count    = var.node-count
      template = "${file("./inventory.tpl")}"
      vars = {
        host_ip  = element(aws_eip.node_eip.*.public_ip, count.index)
        vpc_name = var.vpc_name
      }
    }
    
    #Template Write
    resource "null_resource" "inventory" {
      count = var.node-count
      provisioner "local-exec" {
        command = "echo \"${element(data.template_file.ansible_inventory.*.rendered, count.index)}\" > /tmp/${var.vpc_name}_node_${count.index}.ini"
      }
      depends_on = [data.template_file.ansible_inventory]
    }

And here are the contents of the inventory.tpl that is used:

    [all]
    ${host_ip} StrictHostKeyChecking=no -F /tmp/${vpc_name}_node.cfg'

I would like to use locals to accomplish this and save an individual files per "var.node-count". How do you approach this via templatefile? What do I need to change in the inventory.tpl file? Any help is appreciated.

    locals {
      #count = var.node-count #### count does not work
      ansible_inventory = templatefile("${path.module}/inventory.tpl",
      {
        host_ip  = element(aws_eip.node_eip.*.public_ip, count.index)
        vpc_name = var.vpc_name
      })
    }

Solution

  • This should be possible to achieve with the combination of count, local_file [1] and templatefile built-in function. This should be enough to create what you need:

    resource "local_file" "inventory" {
        count    = var.node-count
        content  = templatefile("${path.module}/inventory.tpl", {
            host_ip  = element(aws_eip.node_eip.*.public_ip, count.index)
            vpc_name = var.vpc_name
        })
        filename = "/tmp/${var.vpc_name}_node_${count.index}.ini"
    }
    

    [1] https://registry.terraform.io/providers/hashicorp/local/latest/docs/resources/file