Multiple Deployments with Terraform Workspaces
In recent months, I've been working more and more with Terraform, deploying to multiple cloud providers and even combining it with Serverless projects (more on that on the next post).
Terraform allows for infrastructure automation in a way Ansible could only dream of doing.
It's incredibly simple, quite predictable, and works seemlessly with all the major cloud providers.
If you make any changes to your Terraform configuration, and run
Terraform will simply alter your current infrastructure to match your new configuration.
But what if you want multiple deployments of your infrastructure, across different regions?
For this we will be using Terraform Workspaces, with a few added improvements.
Example Terraform config - EC2 Instance
Let's look at the following main.tf This configuration would create a t2.micro instance on us-east-1.Let's tweak it a bit and move the region to a variable file.
main.tf: variables.tf: Now when you run terraform apply it will ask you to specify a region. In order to have multiple deployments of the same configuration, we need to create a new workspace. Let's name it dev: Of coures the name dev is arbitrary, you could use whatever you want.
If we try to run terraform apply again, a second instance will be created!
External configuration files
Once your variables start adding up, it gets pretty annoying to fill them in each time you deploy your terraform. You could add them to the command itself as such: But it's much easier to put the environment variables in a file. I name my files WorkspaceName.tfvarsFor our example, I have the file dev.tfvars: Now you can run the following command: But I like to have a single command across all workspaces: The command above simply fetches your current workspace and gets the corresponding variable file.
I've created an example repository with all the relevant files.
My next post will review how you could connect Terraform with Serverless deployments.