mlabouardy / terraform-aws-labs

Terraform template for AWS provider ☁️
MIT License
168 stars 227 forks source link

How do you automatically populate hosts file with ip of created nodes by terraform? #1

Open holms opened 6 years ago

holms commented 6 years ago

Doing this manually is very counter-productive every time. What are the variants to implement this?

jtbonhomme commented 6 years ago

This can be achieved with the terraform "local_exec" plugin like this taking advantage of the .public_ip variable. The idea is to create a text file during provisionning (ie inventory) to be used later by ansible:

resource "null_resource" "ansible-provision" {

  depends_on = ["aws_instance.ec2-master"]

  ##Create Masters Inventory
  provisioner "local-exec" {
    command =  "echo \"[ec2-master]\" > ansible/inventories/iv1"
  }
  provisioner "local-exec" {
    command =  "echo \"\n${format("%s ansible_ssh_host=%s", aws_instance.ec2-master.tags.Name, aws_instance.ec2-master.public_ip)}\" >> ansible/inventories/iv&"
  }
}