terraform:如何在降低 aws_instance 计数时销毁最旧的实例

terraform: How to destroy oldest instance when lowering aws_instance count

给定一对使用

部署的 aws 实例
provider "aws" {
  region     = "us-east-1"
}

resource "aws_instance" "example" {
  count         = 2
  ami           = "ami-2757f631"
  instance_type = "t2.micro"
  tags = {
      Name = "Test${count.index}"
  }
}

降低 count = 1 将销毁最后部署的实例:

Terraform will perform the following actions:

    - aws_instance.example[1]

是否有可能让 terraform 摧毁 第一个实例。即

Terraform will perform the following actions:

  - aws_instance.example[0]

Terraform 正在通过其状态跟踪哪个实例。当您减少 aws_instance 资源上的 count 时,Terraform 将简单地删除后面的实例。虽然这真的不是什么大问题,因为我真的只建议您部署同构实例组,如果您真的需要的话,这些实例可以处理被中断的负载(并且会位于某种形式的负载平衡器机制后面)可以编辑状态文件以在减少实例数量之前重新排序实例。

状态文件被序列化为 JSON,因此您可以直接编辑它(如果您使用的是远程状态,请确保将其上传到您用于远程状态的任何地方)或者更好的是您可以使用Terraform CLI 随 terraform state mv.

提供的第一个 class 编辑远程状态的工具

例如,您可以这样做:

# Example from question has been applied already
# `count` is edited from 2 to 1
$ terraform plan
...
aws_instance.example[1]: Refreshing state... (ID: i-0c227dfbfc72fb0cd)
aws_instance.example: Refreshing state... (ID: i-095fd3fdf86ce8254)

------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  - destroy

Terraform will perform the following actions:

  - aws_instance.example[1]

Plan: 0 to add, 0 to change, 1 to destroy.
...
$
$
$
$ terraform state list
aws_instance.example[0]
aws_instance.example[1]
$
$
$
$ terraform state mv aws_instance.example[1] aws_instance.example[2]
Moved aws_instance.example[1] to aws_instance.example[2]
$ terraform state mv aws_instance.example[0] aws_instance.example[1]
Moved aws_instance.example[0] to aws_instance.example[1]
$ terraform state mv aws_instance.example[2] aws_instance.example[0]
Moved aws_instance.example[2] to aws_instance.example[0]
$
$
$
$ terraform plan
...
aws_instance.example[1]: Refreshing state... (ID: i-095fd3fdf86ce8254)
aws_instance.example: Refreshing state... (ID: i-0c227dfbfc72fb0cd)

------------------------------------------------------------------------

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  ~ update in-place
  - destroy

Terraform will perform the following actions:

  ~ aws_instance.example
      tags.Name: "Test1" => "Test0"

  - aws_instance.example[1]

Plan: 0 to add, 1 to change, 1 to destroy.
...