Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 572
Ebin Davis Avatar asked Mar 08 '23 09:03

Ebin Davis


2 Answers

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
like image 148
danehammer Avatar answered Mar 10 '23 00:03

danehammer


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

like image 39
Ebin Davis Avatar answered Mar 09 '23 23:03

Ebin Davis