Best way currently to create an ansible inventory from terraform

DrM picture DrM · Aug 3, 2017 · Viewed 18k times · Source

I have a long list of machines, all of which are a little different in functionality in a system. I'd like to organize these machines and add to a hosts inventory file automatically so I can run ansible and manage inventory. Are there good solutions out there for this?

I think ansible hosts should looks something like...

[webservers]
someip
someip
[integration]
someip
someip

etc..

After asking the question, I currently am researching output vars and using those to render a template from a file.

Answer

DrM picture DrM · Aug 3, 2017

I figured it out.

data "template_file" "dev_hosts" {
  template = "${file("${path.module}/templates/dev_hosts.cfg")}"
  depends_on = [
    "aws_instance.dev-api-gateway",
    "aws_instance.dev-api-gateway-internal",
    ....
  ]
  vars {
    api_public = "${aws_instance.dev-api-gateway.private_ip}"
    api_internal = "${aws_instance.dev-api-gateway-internal.private_ip}"
  }
}

resource "null_resource" "dev-hosts" {
  triggers {
    template_rendered = "${data.template_file.dev_hosts.rendered}"
  }
  provisioner "local-exec" {
    command = "echo '${data.template_file.dev_hosts.rendered}' > dev_hosts"
  }
}

Then create a template in the file referenced earlier

Contents of example dev_hosts.cfg

[public]
${api_public}


[private]
${api_internal}