terraform - 在 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 状态的内容。
推荐阅读
- io - WebAssembly 可以做 IO 吗?
- javascript - 2 个单独文件中的多个表单验证
- java - 当行的第一列为空时,Excel 写入不起作用
- c# - EF 2.1 核心 IEntityTypeConfiguration 添加默认值
- android - 放置和获取其他课程的额外内容
- reactjs - 使用 NavigatorIOS 时无法显示内容
- java - 带有负数字节的 Java AudioInputStream 跳过总是返回 0
- xml - 没有出现在 android studio 上的视图
- python - 为什么这个答案通过了 Leetcode Q41
- javascript - 箭头函数中的 JavaScript 扩展运算符