What is purpose of Terraform Workspaces
Terraform workspace can be used to create multiple environments. Earlier Terraform used to have concept of environments which was later renamed to worspace.
Terraform has introduced the whole sub-command for managing terraform workspaces. The command looks like
terraform workspace --help
Usage: terraform workspace
New, list, select and delete Terraform workspaces.
Subcommands:
delete Delete a workspace
list List Workspaces
new Create a new workspace
select Select a workspace
show Show the name of the current workspace
Even if you are not using workspaces now terraform creates a workspace called default automatically
Example of Terraform Workspace
- Lets start with sample as mentioned here
- Copy the script to some new folder
- Start by executing the following command
terraform init
- Execute the following command to find the current workspaces
terraform workspace list
and you will observe the following output
terraform workspace list
* default
- With terraform workspace you get variable terraform.workspace which has active workspace name that can be used in interpolation
- I will be changing the resource like
resource "aws_vpc" "mainnet" {
cidr_block = "192.168.0.0/16"
tags = {
Name = "mainnet-${terraform.workspace}"
}
}
- Lets create a new workspace called Dev using command
terraform workspace new Dev
which creates new workspace called as Dev and switches you to Dev Workspace
- Lets check the available workspaces by using command
terraform workspace list
default
* Dev
- Lets see the contents of the folder before apply command
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/27/2019 2:27 PM .terraform
d----- 1/27/2019 2:27 PM terraform.tfstate.d
-a---- 1/27/2019 2:23 PM 981 main.tf
-a---- 1/27/2019 12:33 PM 88 terraform.tfvars
-a---- 1/27/2019 12:24 PM 180 variables.tf
- Now executing terraform apply will create a new folder under terraform.tfstate.d as Dev
- Lets now create new workspace called as QA using command
terraform workspace new QA
- Change the values in the terraform.tfvars file and execute terraform apply
terraform apply .
-
Now examine your aws account and you will be observing two networks created from same terraform folder with workspaces.
-
State files will be stored in terraform.tfstate.d folder.
-
You can also extend your state files by using backends as we have discussed in the earlier blog item by adding backends here.
-
For further reading refer here