【问题标题】:In Terraform is it possible to move to state from one workspace to another在 Terraform 中是否可以将状态从一个工作区移动到另一个工作区
【发布时间】:2021-07-02 21:24:01
【问题描述】:

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

【问题讨论】:

    标签: terraform terraform-provider-aws


    【解决方案1】:

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

    假设您正在使用 S3 远程 backend 和 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 应用没有改变任何东西。

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

    当你还在默认工作区时拉状态

    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:我强烈推荐阅读更多关于managing Terraform state的信息。

    【讨论】:

    • 拥有巨大状态的你们可以使用这个命令来清理default中的垃圾:terraform state list | xargs -n 1 terraform state rm
    【解决方案2】:

    根据后端,Terraform 可能能够自行进行迁移。

    为此,只需在terraform 块中更新您的后端配置,然后运行以下命令以自动迁移状态:

    terraform init -migrate-state
    

    这样做会将定义的所有工作区的状态从旧复制到新。

    我可以确认这适用于 Terraform Cloud,即使使用前缀定义了多个工作区。

    【讨论】:

      猜你喜欢
      • 2014-07-03
      • 2021-12-19
      • 1970-01-01
      • 2011-05-07
      • 2021-06-16
      • 2020-05-23
      • 2014-05-25
      • 1970-01-01
      • 2012-04-24
      相关资源
      最近更新 更多