Terraform:你什么时候会手动更改状态?

Terraform: when would you manually change the state?

根据the docs

As your Terraform usage becomes more advanced, there are some cases where you may need to modify the Terraform state.

什么情况下你会想直接改变terraform的状态?

与更改 terraform 代码本身相比,这样做似乎是一种非常危险的做法。

您认为修改状态文件可能很危险,因为这可能会损坏状态文件或导致 Terraform 做您不希望它做的事情,因为状态文件从您的更改到它所针对的提供者的实际状态。

但是,有时您可能想要修改状态文件,例如添加您在 Terraform 状态文件之外创建的资源(完全在 Terraform 之外创建或仅使用不同的状态文件创建),使用terraform import command or for renaming Terraform config resources using the terraform state commands.

例如,如果您开始直接使用以下内容定义资源:

variable "ami_name" {
  default = "ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"
}

variable "ami_owner" {
  default = "099720109477" # Canonical
}

data "aws_ami" "ubuntu" {
  most_recent = true

  filter {
    name   = "name"
    values = [var.ami_name]
  }

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

  owners = [var.ami_owner]
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"

  tags {
    Name = "HelloWorld"
  }
}

然后您决定将其重构为一个模块,以便其他人可以用类似的方式调用它:

module "instance" {
  ami_name  = "my-image-name-*"
  ami_owner = "123456789"
}

当你 运行 重构 Terraform 后的计划会告诉你它想要删除 aws_instance.web 资源并巧合地创建一个名为 module.instance.aws_instance.web 的具有相同参数的资源。

如果您想在不因 Terraform 破坏旧资源并将其替换为新资源而造成中断的情况下执行此操作,那么您只需编辑状态文件以更改资源名称:

terraform state mv aws_instance.web module.instance.aws_instance.web

如果您随后 运行 一个计划,它将显示一个空的更改,成功完成重构而不会对您部署的实例造成任何影响。