When starting of I was using the default workspace. Due to increased complexity I would like to use multiple workspaces. I want to move what is in default workspace into its own workspace or rename the default workspace as another workspace. How can I do this?
Yes it is possible to migrate state between workspaces.
I'm assuming that you are using S3 remote backend and terraform version >= 0.13 Let's see how this state surgery looks like:
Sample resource config that needs to be migrated between workspaces:
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 = ""
}
}
Let's initialise the backend for the default
workspace and 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
So, as you can see a local file was already created and the state is stored in the default workspace. Terraform apply didn't change anything.
Now, we want to migrate to a new workspace:
Pull the state while you are still in the default workspace
terraform state pull > default.tfstate
Create a new workspace; let's call it test
terraform workspace new test
Created and switched to workspace "test"!
If you try to run terraform state list
, you should not see any state.
Let's push the state to newly created workspace and see what's in the state; also what happens when we 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.
Your local_file.foo
has been migrated to the test
workspace.
Don't forget to switch back to the default
workspace and remove state references for this file.
terraform workspace select default
terraform state rm local_file.foo
Removed local_file.foo
Successfully removed 1 resource instance(s).
PS: I would highly recommend reading more about managing Terraform state.