在 Terraform 中是否可以从一个工作区转移到另一个工作区

kum*_*mar 1 terraform terraform-provider-aws

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

小智 6

每次新工作区都是空的时,所有预览答案都不适合我。为了填充它,您需要-state按照文档使用。 https://www.terraform.io/cli/commands/workspace/new

那么有效的是:

  • 创建本地备份 terraform state pull > default.tfstate
  • 然后通过注释后端块切换到本地terraform init -migrate-state
  • 使用创建新工作区terraform workspace new -state=default.tfstate newspace这会将其复制defaultnewspace
  • 做一个terraform plan检查
  • 取消注释后端块以切换回云中,然后运行terraform init -migrate-state以迁移云中的新工作区
  • 执行terraform planterraform workspace list进行检查。


bha*_*hia 5

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

假设您使用的是 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 = ""
  }
}
Run Code Online (Sandbox Code Playgroud)

让我们初始化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
Run Code Online (Sandbox Code Playgroud)

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

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

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

terraform state pull > default.tfstate
Run Code Online (Sandbox Code Playgroud)

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

terraform workspace new test
Created and switched to workspace "test"!
Run Code Online (Sandbox Code Playgroud)

如果您尝试运行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.
Run Code Online (Sandbox Code Playgroud)

繁荣!您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).
Run Code Online (Sandbox Code Playgroud)

PS:我强烈建议阅读更多关于管理 Terraform 状态的信息

  • 那些拥有庞大状态的人,可以使用此命令来清理 `default` 中的残留物: ```terraform state list | xargs -n 1 地形状态 rm``` (4认同)