Terraform workspaces are similar to the concept of namespaces, which enables us to manage multiple deployments of the same configuration (like using the same configs but for development environment, production environment, testing environment, etc..)
Note: its not meant to be used for creating different components in separate workspaces as it would case conflict to the state file
terraform.workspace
Say you want to create an EC2 instance, but with varying sizes depending on the environment. First, define in the variables file (like in the second code block) a flag which can be used as an indicator whether it’ll be created for development or production. Here the lookup function was used to retrieve the value from the created variable map using the current active workspace
resource "aws_instance" "webserver" {
ami = var.ami
instance_type = lookup(var.instance_type, terraform.workspace)
tags = {
Environment = terraform.workspace
}
}
variable "ami" {
default = "ami-24e140119877avm"
}
variable "region" {
default = "ca-central-1"
}
variable "instance_type" {
default = "t2.micro"
}
variable "instance_type" {
type = map
default = {
"development" = "t2.micro"
"production" = "m5.large"
}
}
There can be other ways to implement a resource using the terraform.workspace
check the following for more examples
terraform workspace new
terraform workspace list # also shows which workspace you are currently in
terraform workspace show
terraform workspace select
terraform workspace delete