删除Terraform的tfstate文件会导致什么结果

执行Terraform创建资源时, 将创建名为tfstate的文件。

根据以下公式文件:

https://www.terraform.io/docs/state/purpose.html
https://www.terraform.io/docs/state/index.html

https://www.terraform.io/docs/state/purpose.html 可查看有关Terraform状态的目的的信息
https://www.terraform.io/docs/state/index.html 可查看有关Terraform状态的详细说明

Terraform需要保存管理的基础设施和配置的状态。Terraform使用这个状态来映射实际资源到配置,并跟踪元数据以提高大规模基础设施的性能。

Terraform通常使用配置来确定依赖关系的顺序。但是,如果从Terraform配置中删除资源,则Terraform需要知道如何删除该资源。Terraform将检查是否存在配置中不存在的资源映射,并计划将其销毁。但是,由于配置不存在,无法仅凭配置确定顺序。

为确保正确操作,Terraform保留了状态中最新依赖关系集的副本。目前,当Terraform从配置中删除一个或多个项时,可以从状态中确定正确的销毁顺序。

删除此tfstate文件将使资源的添加和删除变得非常困难。

试验一下

参考官方示例代码适当创建EC2实例。

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
}

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

  tags = {
    Name = "HelloWorld"
  }
}

顺便一提,Canonical是开发Ubuntu的公司。

如果按照公式文档的指示进行terraform plan,那么会发生以下情况:

Warning: Interpolation-only expressions are deprecated

被责备是因为这种写法在现行的Terraform 0.12中不被推荐。(正如错误信息所写的那样)

data.aws_ami.ubuntu.id

只要写出这个,就不会被生气了。

试着执行。

执行terraform apply时,通常会在当前目录执行。

terraform.tfstate
terraform.tfstate.backup

会生成一个名为”文件”的文件。
查看其内容,可以看到以下格式的json文件。

]$ cat terraform.tfstate
{
  "version": 4,
  "terraform_version": "0.12.16",
  "serial": 3,
  "lineage": "xxxxxxxxxxxxxxxxxxxx",
  "outputs": {},
  "resources": [
    {
      "mode": "data",
      "type": "aws_ami",
      "name": "ubuntu",
      "provider": "provider.aws",
      "instances": [
        {
          "schema_version": 0,
          "attributes": {
            "architecture": "x86_64",
            "block_device_mappings": [
              {
                "device_name": "/dev/sda1",
                "ebs": {
                  "delete_on_termination": "true",
                  "encrypted": "false",
                  "iops": "0",
~略~

如果删除它,将无法执行terraform destroy,除非创建与此文件内容完全相同的文件再试试。

$ terraform destroy
data.aws_ami.ubuntu: Refreshing state...

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

Terraform will perform the following actions:

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

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

由于没有参照状态,无法通过terraform删除所创建的资源。

如果你使用Terraform创建的资源,如果在管理控制台或其他方式上进行更改,那么它将与tfstate文件不一致,导致无法执行destroy或apply操作。因此,如果你使用Terraform,tfstate文件的管理非常重要。(我在构建中误删了一次,几乎丧命了,请保密)

广告
将在 10 秒后关闭
bannerAds