Wednesday 8 June 2022

Terraform Workspaces

 


By default, there is one state file (terraform.tfstate) per configuration directory. Sometimes, we want to reuse the same configuration files for multiple projects. Instead of creating a directory for each project and copy-pasting files, we can use Terraform's feature called workspaces. Each workspace has its own, isolate state. When in particular workspace, terraform plan can see only its state.

When we create a configuration file, before explicitly creating any workspaces, Terraform implicitly creates a workspace named default:

$ terraform console
> terraform.workspace
default

To create a workspace:

$ terraform workspace new ProjectA

To list all workspaces:

$ terraform workspace list
  default
* ProjectA
  ProjectB

Asterisk indicates the currently active workspace.

To switch to another workspace we need to use select command:

$ terraform workspace select default
Switched to workspace "default".
$ terraform workspace select ProjectB 
Switched to workspace "ProjectB".

terraform.workspace variable contains the name of the current workspace and it can be used in configuration files:

variables.tf:

variable region {
    default = "eu-west-1"
}

variable instance_type {
    default = "t2.micro"
}

variable ami {
    type = map
    default = {
        "ProjectA" = "ami-0123456789"
        "ProjectB" = "ami-9876543210"
    }
}

main.tf:

resource "aws_instance" "my-server" {
    ami = lookup(var.ami, terraform.workspace)
    instance_type = var.instance_type
    tags = {
        Name = "terraform.workspace"
    }
}

Terraform creates one state file for each workspace. They are stored in a directory named terraform.tfstate.d:

$ tree terraform.tfstate.d/
terraform.tfstate.d/
|--ProjectA
|       `-- terraform.tfstate
`--ProjectB
        `-- terraform.tfstate

---

No comments: