获取 terraform 以忽略已停止实例的 "associate_public_ip_address" 状态

Get terraform to ignore "associate_public_ip_address" status for stopped instance

我有一个简单的 AWS 部署,其中包含 vpc、public 子网、路由和安全组。 运行 terraform apply 将启动一个 AWS 实例,我将该实例配置为关联一个 public IP。创建实例后,我 运行 terraform plan 它正确地说一切都是最新的。目前没有问题。

我们有一个管理节点,如果该实例在一段时间内未使用,作为一种节省成本的措施,它将关闭该实例。

问题是:当我 运行 terraform plan 关闭该实例后,aws 提供商会看到所有配置正确,但由于 public IP 已被释放, associate_public_ip_address 的值不再匹配 terraform 配置中的配置,因此 terraform 想要删除并重新创建该实例:

associate_public_ip_address: "false" => "true" (forces new resource)

有没有办法让 Terraform 只忽略那个参数?

此问题与 https://github.com/hashicorp/terraform/issues/7262 略有相关。但就我而言,我不想设置预期状态,我只想告诉 terraform 忽略那个参数,因为它现在 没有关联也没关系,只要它被配置为关联启动时

(我在写这个问题时想到了这一点:我还没有尝试过将子网配置为自动为其中启动的实例关联 public ip。可以想象,通过让子网自动执行此操作,并删除来自 "aws_instance" 的选项,我也许可以让 terraform 不注意那个值...但我对此表示怀疑。)

您可以使用 lifecycle block to ignore certain attribute changes.

使用它,最初使用为该属性提供的值创建资源。在后续计划、应用等操作中,Terraform 将忽略对该属性的更改。

如果我们在生命周期块中添加对 associate_public_ip_address 的忽略,停止的实例将不再触发新资源。

请注意,如果您更改任何其他需要新实例的参数,已停止的实例将被终止并替换。

示例基于 Terraform aws_instance example code :

provider "aws" {
  region = "us-west-2"
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["099720109477"] # Canonical account ID
}

resource "aws_instance" "web" {
  ami           = "${data.aws_ami.ubuntu.id}"
  instance_type = "t2.micro"
  associate_public_ip_address = "true"
  tags {
    Name = "HelloWorld"
  }

  lifecycle {
    ignore_changes = ["associate_public_ip_address"]
  }
}