Terraform Workspace

Terraform Workspace

Q) Why to use terraform workspace OR what is the benefit of using workspaces in terraform?

  1. Every initialized working directory have atleast one workspace called as default workspace.
  2. Mainly terraform workspaces are used to make the different isolated working directory for terraform.
  3. Mainly used for making same configuration files that .tf files for different environments called as Dev, QA, Prod etc.
  4. Workspaces are separate instances of state data that can be used from the same working directory, Means there will be different state files created for different workspaces but the .tf files will be same.

Step1 : Create a new terraform folder name as terrform2 and create a new file main.tf in it with below code snippet:

provider “aws”{
profile = “user1”
region = “us-east-1”
}

Commands executed:

  1. terraform init : initialized the providers plugin terraform workspace list : this will give the list of workspaces and in which workspace you are working on currently.
  2. terraform workspace new dev : Development environment workspace
  3. terraform workspace new qa : QA environment workspace
  4. terraform workspace new prod: Production environment workspace

Above commands create a new three workspaces in the directory. Whenever you are creating a new directory by default it will be get selected and you current working directory will be your new directory. terraform workspace select dev: To change the working directory select keyword is used.

2.jpg

Q) How we can now the creation of instances is in which workspaces ANS ) There is an Interpolation variable like ${terraform.workspace} which add the workspace name.

Step2 : Now run a same main.tf file for 3 different workspaces Dev, Qa, Prod

3.jpg

Commands executed: For Dev Workspace: 1) terraform workspace select dev **

2) terraform init

3) terraform validate

4) terraform plan

5) terraform apply OR terraform apply –auto-approve

6) terraform destroy –auto-approve

same commands are executed for every **workspace and state files are created and 3 different instances are created in AWS like below:

AWS Console :

3a.jpg

4.jpg

NOTE: if we are executing same main.tf again in same workspace like dev the there will be no changes in the infrastructure.

5.jpg

terraform state list : List all the resources (EC2 instance, VPC, subnet etc…..) created in state file