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

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

回答

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

假设您使用的是 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 状态的信息。


以上是在Terraform中是否可以从一个工作区转移到另一个工作区的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>