Skip to content

Instantly share code, notes, and snippets.

@hectorcanto
Last active April 5, 2024 19:38
Show Gist options
  • Save hectorcanto/71f732dc02541e265888e924047d47ed to your computer and use it in GitHub Desktop.
Save hectorcanto/71f732dc02541e265888e924047d47ed to your computer and use it in GitHub Desktop.
Produce an Ansible inventory from a Terraform template
data "template_file" "inventory" {
template = "${file("inventory.tpl")}"
vars {
backend_ip = "${aws_instance.backend.public_ip}"
frontend_ip = "${aws_instance.frontend.public_ip}"
landing_ip = "${aws_instance.landing.public_ip}"
key_path = "${var.instance_key_path}"
}
}
resource "null_resource" "update_inventory" {
triggers {
template = "${data.template_file.inventory.rendered}"
}
provisioner "local-exec" {
command = "echo '${data.template_file.inventory.rendered}' > ../inventory"
}
}
[backend]
${backend_ip}
[frontend]
${frontend_ip}
[landing]
${landing_ip}
[all:vars]
ansible_ssh_private_key_file = ${key_path}
ansible_ssh_user = ubuntu
@ravibhure
Copy link

ravibhure commented Jun 26, 2020

you can use local_file with the list with more host vars

resource "local_file" "ansible_hosts" {
  count   = "${var.customer_plan == "micro" ? "1" : "0"}"

  content = "[fenodes]\n${join("\n",
            formatlist(
              "%s ansible_host=%s is_scheduler=true",
              profitbricks_server.fe.*.name,
              profitbricks_server.fe.*.primary_ip
            )
            )}\n\n[benodes]\n${join("\n",
            formatlist(
              "%s ansible_host=%s",
              profitbricks_server.be.*.name,
              profitbricks_server.be.*.primary_ip
            )
            )}\n\n[dbnodes]\n${join("\n",
            formatlist(
              "%s ansible_host=%s metrics_aggregator=true",
              profitbricks_server.db.*.name,
              profitbricks_server.db.*.primary_ip
            )
            )}\n\n[cachenodes]\n${join("\n",
            formatlist(
              "%s ansible_host=%s cache_role=master",
              profitbricks_server.db.*.name,
              profitbricks_server.db.*.primary_ip
            )
            )}\n\n[all:vars]\nansible_user=root\nansible_ssh_pass=${var.image_password}\nansible_private_key_file=configs/ssh/id_rsa\nansible_ssh_common_args='-o StrictHostKeyChecking=yes'"
  filename = "${var.customer_name}-${var.customer_env}-host"

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment