Migrate Terraform workspace
Terraform is a great tool for infrastructure as a code. It can support thousands of resources in a single script. However to reduce blast radius we should create separate terraform repo. Also, there are cases when you have to move from one stage (dev) to another stage (test) in the same cluster.
Statefile Path
Devops team creates a separate state file for each of the stages. This works well & ensures a separate location for each state. However, We recently had an incident where we removed entire terraform objects.
Steps to Migrate
This is onetime activity.
terraform init -backend-config=backend/common.hcl
terraform workspace list
terraform state list
terraform state pull > default.statefs
terraform workspace create test
terraform state push default.statefs
terraform state list
Cleanup (Optional)
If you are planning to use the older workspace as actual resources, you should perform cleanup there. Usually, this scenario seems to be rare. However, it is good to be noted.
terraform workspace select default
terraform state rm <resources>
Change in Pipeline
Add workspace command as mentioned below:
pre_build:commands:- echo Entered the pre_build phase...- cd $TF_DIR- terraform init -backend-config=backend/common.hcl --upgrade- terraform workspace select $STAGE || terraform workspace new $STAGE
Reference: