Terraform workspaces – avoid redundancy

Terraform organizes infrastructure through workpaces, that includes maintaining separate remote state for each environment.

Terraform workspaces starts with a single workspace named “default”. This workspace is special both because it is the default and also because it cannot ever be deleted. we will be creating new workspaces for each environment as opposed to maintaining separate folders for each caller module. 

Refer to terraform documentation here for more information

  • Benefits of using terraform workspaces : 
    • Workspaces helps managing environment specific variables efficiently without having to duplicate the terraform code.
    • Multiple workspaces allows multiple backend states to be associated with a single configuration

Lets look at a simple example, create S3 bucket in dev, qa and prod accounts from a single code repository without code duplication.

Here is project code structure before we go into details

Terraform Workspaces

Key different between workspaces based project and non workspaces based project is the backend files. these files contain backend state location for each environment, typically this information is provided through Provider.tf file and in this case we moved it out into backend files.

Here is Provider.tf file. this is the minimum information that is required

Commands to initialize workspace and run the terraform

#initialize env specific workspace , pass appropriate backend file as an argument. 
terraform init -backend-config=backends/prod-env.tf

#create new workspace ( from command line)
terraform workspace new "dev" 

#change to an existing workspace
terraform workspace select "dev" 

#then run terraform init, plan & apply as you would normally do in any terraform project
terraform plan 
terraform apply

Terraform workspaces are very simple to implement and helpful when you are dealing with multiple environments and multiple accounts.

Here is the complete source code in my git repo

For a better practical example, go to this article on AWS Transfer For SFTP.


Leave a Reply

Your email address will not be published. Required fields are marked *