Reputation: 361
after running 'terraform apply' to create minimal ec2 configuration with aws_eip and provisioner local-exec comand to log the instance's ip in to the log-file, the logged ip differs from the ip assigned to the created instance
example.tf:
provider "aws" {
access_key = ""
secret_key = ""
region = "us-east-1"
}
resource "aws_instance" "example" {
ami = "ami-b374d5a5"
instance_type = "t2.micro"
provisioner "local-exec" {
command = \
"echo ${aws_instance.example.public_ip} >ip_address.txt"
}
}
resource "aws_eip" "ip" {
instance = "${aws_instance.example.id}"
}
expected result is: address in log file ip_addtess.txt is = elasticIp in created ec2 instance;
actual is: ip in log file: 34.239.128.148 ip ec2 created instance: 3.216.120.212
Upvotes: 1
Views: 794
Reputation: 74219
When assigning an Elastic IP address to an instance using aws_eip
, any operations that will use the allocated Elastic IP address must use aws_ip.ip.public_ip
instead of aws_instance.example.public_ip
, because the latter is the normal public IP address assigned to the instance when it started, while the Elastic IP address is assigned asynchronously afterwards.
In this case, that would mean moving the provisioner into the aws_ip
resource instead:
resource "aws_eip" "ip" {
instance = "${aws_instance.example.id}"
provisioner "local-exec" {
command = "echo ${self.public_ip} >ip_address.txt"
}
}
Though if you are writing the IP address to a file for the purposes of using it elsewhere, it may be better to export it as an output value instead:
output "public_ip" {
value = "${aws_eip.ip.public_ip}"
}
Upvotes: 1