Centered image

Terraform Workspaces are used to manage your state files in different environments.

In this Terraform workspace demo I’m going to be using the files from demo.3 from the following git repo https://github.com/terraformtraining/terraform.git and using version > 0.10 of Terraform.

[markb@feddy demo.3] $ terraform -v
Terraform v0.10.0

So to start off with I have the following files within my working folder.

-rw-rw-r--. 1 markb markb 246 Jul 29 12:20 deploy_website.sh
-rw-rw-r--. 1 markb markb 714 Jul 29 12:21 instance.tf
-rw-rw-r--. 1 markb markb 128 Jul 30 15:44 provider.tf
-rw-rw-r--. 1 markb markb 101 Aug 11 13:35 terraform.tfvars
-rw-rw-r--. 1 markb markb 307 Jul 30 15:44 vars.tf

This simply spins up an AWS micro instance, pushes a script to the instance that creates a websever. But say we wanted to test to see if this worked first. Well we could first create a new workspace called dev enter this workspace and run terraform apply this would create a completely new state file and we can safely work in this workspace without disrupting any other resources. Whenever we use Terrafrom without workspaces we are using the default workspace as shown below.

[markb@feddy demo.3] $ terraform workspace show
default

The Terraform workspaces commands are shown below.

show      Show the current workspace name.
list      List workspaces.
select    Select a workspace.
new       Create a new workspace.
delete    Delete an existing workspace.

So lets create a new dev workspace by running terraform workspace new dev and then run terraform apply. As we can see below instead of creating a terraform.tfstate file in the working folder Terraform created a new folder called terraform.tfstate.d/dev and places the state file within that.

├── deploy_website.sh
├── instance.tf
├── provider.tf
├── terraform.tfstate.d
│   └── dev
│       └── terraform.tfstate
├── terraform.tfvars
└── vars.tf

Ok so our webserver is now up and we are happy with the results, lets create and switch to a prod workspace. So we run terraform workspace new prod. This automatically places us in the prod workspace.

[markb@feddy demo.3] $ terraform workspace list
default
dev
* prod

Now lets run terraform apply again. Note if we were not using a different workspace Terraform would say no changes were needed as the remote and local state would match.

├── deploy_website.sh
├── instance.tf
├── provider.tf
├── terraform.tfstate.d
│   ├── dev
│   │   └── terraform.tfstate
│   └── prod
│       └── terraform.tfstate
├── terraform.tfvars
└── vars.tf

And now we have a prod folder with a new state file. So as we can see above we can use Terraform workspaces to manage differences between development, staging, and production. You can also backup the remote state of each workspace to S3, see here for a full guide.

Don’t forget to go back into each workspace and run terraform destroy or you may get charged by Amazon.