Ebin Davis
Ebin Davis

Reputation: 6139

How to fetch the Public IP of the newly launched machine using Terraform

I have created two instances (Instance-1 and Instance-2) in AWS using Terraform. I installed Ansible on Instance-1 in the same script and I want to push a playbook to Instance-2 from Instance-1.

I want to specify the public-IP, username and key path to the Ansible Host file inside Instance-1 where I installed Ansible.

How can I fetch the public-IP of Instance-2 for specifying the aforementioned attributes in the Ansible host file ?

Upvotes: 5

Views: 9094

Answers (2)

danehammer
danehammer

Reputation: 416

If you're like me, with terraform and ansible runs as separate steps in a bigger orchestration, use terraform outputs to save off the IP address(es) you need during ansible. For example, we provision a whole cluster with terraform, only allowing SSH from a bastion host. I use the following to save off the bastion's IP address (it's behind an elastic IP):

output "bastion.ip" {
  value = "${aws_eip.bastion.public_ip}"
}

Then to retrieve it after terraform apply:

bash-4.3# terraform output bastion.ip
52.1.2.3

Upvotes: 7

Ebin Davis
Ebin Davis

Reputation: 6139

You can fetch the public_ip of the launched instances through terrraform using,

resource "aws_instance" "web" {

....

provisioner "local-exec" {

command = "echo ${aws_instance.web.public_ip} >> /path/to/save"

}

https://www.terraform.io/docs/provisioners/local-exec.html

Upvotes: 1

Related Questions