Terraform,aws_eip,预配器,本地执行器,不一致的IP地址

时间:2019-05-13 19:43:25

标签: terraform

运行“ terraform apply”以使用aws_eip和Provisioner local-exec com创建最小的ec2配置并将实例的ip登录到日志文件后,记录的ip与分配给创建的实例的ip不同

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}"
    }

预期结果是: 日志文件ip_addtess.txt中的地址在创建的ec2实例中为= elasticIp;

实际是:日志文件中的ip:34.239.128.148         ip ec2创建的实例:3.216.120.212

1 个答案:

答案 0 :(得分:0)

使用aws_eip为实例分配弹性IP地址时,将使用分配的弹性IP地址的任何操作都必须使用aws_ip.ip.public_ip而非aws_instance.example.public_ip,因为后者是正常的实例启动时分配给实例的公共IP地址,而弹性IP地址随后异步分配。

在这种情况下,这意味着将预配器移至aws_ip资源中:

resource "aws_eip" "ip" {
  instance = "${aws_instance.example.id}"

  provisioner "local-exec" {
    command = "echo ${self.public_ip} >ip_address.txt"
  }
}

尽管如果您要将IP地址写入文件以在其他地方使用,则最好将其导出为output value

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