首页 > 解决方案 > 在 Terraform 中是否可以将状态从一个工作区移动到另一个工作区

问题描述

开始时我使用的是默认工作区。由于复杂性增加,我想使用多个工作区。我想将默认工作区中的内容移动到它自己的工作区或将默认工作区重命名为另一个工作区。我怎样才能做到这一点?

标签: terraformterraform-provider-aws

解决方案


是的,可以在工作区之间迁移状态。

假设您使用的是 S3 远程后端和 terraform 版本 >= 0.13 让我们看看这个状态手术的样子:

需要在工作空间之间迁移的示例资源配置:

provider "local" {
  version = "2.1.0"
}

resource "local_file" "foo" {
  content  = "foo!"
  filename = "foo.bar"
}

terraform {
  backend "s3" {
    bucket         = ""
    region         = ""
    kms_key_id     = ""
    encrypt        = ""
    key            = ""
    dynamodb_table = ""
  }
}

让我们初始化default工作区的后端,然后apply

terraform init
<Initialize the backend>

terraform workspace list
* default

terraform apply
local_file.foo: Refreshing state... [id=<>]

Apply complete! Resources: 0 added, 0 changed, 0 destroyed

因此,正如您所见,本地文件已经创建,并且状态存储在默认工作区中。Terraform apply 没有改变任何东西。

现在,我们要迁移到一个新的工作区:

在您仍处于默认工作区时拉取状态

terraform state pull > default.tfstate

创建一个新的工作区;让我们称之为test

terraform workspace new test
Created and switched to workspace "test"!

如果您尝试运行terraform state list,您应该看不到任何状态。让我们将状态推送到新创建的工作区,看看状态是什么;也发生了什么,当我们apply

terraform state push default.tfstate

terraform state list
local_file.foo

terraform apply
local_file.foo: Refreshing state... [id=<>]

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

繁荣!您local_file.foo已迁移到test工作区。

不要忘记切换回default工作区并删除此文件的状态引用。

terraform workspace select default
terraform state rm local_file.foo
Removed local_file.foo
Successfully removed 1 resource instance(s).

PS:我强烈建议阅读更多关于管理 Terraform 状态的内容。


推荐阅读