Output Public IP is Not Actual Public IP

原本我看網路上的範例,說這樣可以在 terraform apply 之後,取得 instance 的 IPv4 public IP 字串:

output "instance_ips" {
  value = [aws_instance.example.*.public_ip]
}

但是實際測試之後,發現收到的 IP 與在 console 裡看到的不同

我又查了一陣子,才看到這個解法:

Public IP output is different than actual public IP? · Issue #5682 · terraform-providers/terraform-provider-aws · GitHub

  1. AWS provider creates EC2 instance and refreshes the EC2 instance detail into the Terraform state (including the pre-EIP public_ip)
  2. AWS provider associates EIP with EC2 instance and refreshes EIP association detail into the Terraform state

The problem is that the output referencing aws_instance.stage.public_ip will read the public_ip attribute of the aws_instance as it was saved in the Terraform state, before the EIP association ever happened.

照留言內容,把 aws_instance.example.*.public_ip 改成 aws_eip_association.example.public_ip 之後,收到的就是實際使用的 public IP 了