How to use Workspaces in Terraform?
Terraform worksapces is a very logical concept where you can have multiple states of your infrastructure configuration. To put this in simple words if you are running an infrastructure configuration in development environment then the same infrastructure can be run in the production environment.
The main benefit of terraforming workspaces we get is we can have more than one state associated with a single terraform configuration.
If you have not defined any workspace then there is always a default
workspace created by terraform, so you always work in a default workspace of terraform. You can list the number of terraform workspaces by running the command terraform workspace show
. Also, you can not delete the default
workspace
Here is our Table of Content on How to work with Terraform workspaces
- How to create a new Terraform workspace
- How to List all the Terraform workspaces
- How to Show Terraform workspaces
- How to Switch Terraform workspaces
- How to use the name of Current Workspace using ${terraform.workspace} Interpolation
- Terraform workspace and terraform.tfstate, terraform.tfstate.d
- When to use multiple terraform workspaces?
1. How to create a new Terraform workspace
To create a terraform workspace first you make sure that you have installed terraform. After that, you simply need to run the following terraform workspace command -
1terraform workspace new dev
Here are few points to keep in mind -
- To create a workspace you must type in the keyword
workspace
after terraform - You must also type in
new
for creating a new workspace - The third and last thing is your workspace name, in the above command I have taken the workspace name as
dev
1.1 Create one more workspace with name test
To get a better understanding of workspace and how it isolates then I would highly recommend creating one more workspace where we run the terraform
commands respectively on each workspace without affecting their states
Here is the command for creating another workspace with the name test
1 terraform workspace new test
2. How to List all the Terraform workspaces?
Now in step 1 we have seen how to create a new workspace in terraform. But then how to list all the workspaces which we have created previously.
So to list all the available workspaces use the following terraform command -
1terraform workspace list
The above command will list down all the available workspaces including the default
workspace also
The active workspace is always prefixed with a star.
3. How to Show Terraform workspaces?
Now we know how to create a terraform workspace and how to list all the available workspace in terraform.
But is there a way to show active workspace?
Terraform provides a command terraform workspace show
which can help you to show the active running workspace in which you are working.
1terraform workspace show
Here is one example screenshot below which will tell you that test
is active running state
4. How to switch Terraform workspaces?
It might be possible that you have created multiple workspaces to isolate your infrastructure code and you want to switch between the workspaces to apply your infrastructure changes.
So to switch the workspace you should following terraform command -
1terraform workspace select test
The above terraform command will make a switch to test
workspace. In your case, you simply need to put your workspace name to make the switch between the workspaces
5. How to use the name of Current Workspace using ${terraform.workspace} Interpolation?
While working with longer terraform infrastructure code it often needed to name or tag your resources based on the environment profile such as dev, test, stage, prod, etc.
With the help of ${terraform.workspace}
interpolation sequence you can use the current workspace name to define terraform locals.
Here is a simple example of provisioning a simple EC2 instance -
- I have defined a terraform local
instance_name
- The terraform local have a name prefixed with the current workspace name .i.e. - "${terraform.workspace}-instance"
- And the terraform local is used to tag the
aws_instance
1 provider "aws" {
2 region = "eu-central-1"
3 access_key = "AKIATspmbXB2EPCJFO4Y"
4 secret_key = "AH9Hw//EfW6OJM8EFrWllkKdlgovpihIvYpu9TTxr"
5
6}
7
8locals {
9 instance_name = "${terraform.workspace}-instance"
10}
11
12resource "aws_instance" "ec2_example" {
13
14 ami = "ami-0767046d1677be5a0"
15
16 instance_type = var.instance_type
17
18 tags = {
19 Name = local.instance_name
20 }
21}
6. Terraform workspace and terraform.tfstate, terraform.tfstate.d
Whenever you work with terraform workspace and when you create multiple workspaces then you will get one directory created for each workspace inside your terraform project.
Here is an example where I have created two workspace - dev, test
So with each workspace, you end up with its own terraform.tfstate
and terraform.tfstate.d
file which will help you to separate and isolate the infrastructure behavior based on your configuration settings.
7. When to use multiple terraform workspaces?
Here are some key points where I felt you should use terraform workspaces -
- When you feel that you need a parallel, distinct copy of your infrastructure which you can test and verify in the development, test, and staging environment before putting it into the production environment.
- Secondly terraform workspaces acts as feature branch. If you have ever worked with a versioning tool then you might be familiar with
main
ormaster
where every developer merges their code from thefeature
branch. So assume thedefault
workspace as yourmain
ormaster and the
workspaces` as your featured branch where you will test and verify your changes. - Do not presume that with terraform workspaces you can separate or decompose your infrastructure component. Terraform workspaces are not meant to decompose your infrastructure. If you really want to separate or decompose your infrastructure then I would recommend using a separate set of configuration and backend to achieve that.
- If you have your infrastructure where each deployment requires you to put different setup credentials then you should not use Terraform workspaces for that.
Read More - Terragrunt -
Posts in this Series
- Securing Sensitive Data in Terraform
- Boost Your AWS Security with Terraform : A Step-by-Step Guide
- How to Load Input Data from a File in Terraform?
- Can Terraform be used to provision on-premises infrastructure?
- Fixing the Terraform Error creating IAM Role. MalformedPolicyDocument Has prohibited field Resource
- In terraform how to handle null value with default value?
- Terraform use module output variables as inputs for another module?
- How to Reference a Resource Created by a Terraform Module?
- Understanding Terraform Escape Sequences
- How to fix private-dns-enabled cannot be set because there is already a conflicting DNS domain?
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Variables - Locals,Input,Output
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11