Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different environments for Terraform (Hashicorp)

Tags:

terraform

I've been using Terraform to build my AWS stack and have been enjoying it. If it was to be used in a commercial setting the configuration would need to be reused for different environments (e.g. QA, STAGING, PROD).

How would I be able to achieve this? Would I need to create a wrapper script that makes calls to terraform's cli while passing in different state files per environment like below? I'm wondering if there's a more native solution provided by Terraform.

terraform apply -state=qa.tfstate 
like image 502
n00b Avatar asked May 03 '16 13:05

n00b


People also ask

What feature of Terraform allows you to deploy multiple environments with independent states?

Workspaces allow you to deploy multiple distinct instances of the same infrastructure configuration without storing them in separate backends.

How do you separate environmental Terraforms?

Separate configuration To split the configuration, first make a copy of main.tf and name it dev.tf . Rename the main.tf file to prod.tf . You now have two identical files. Open dev.tf and remove any references to the production environment by deleting the resource blocks with the prod ID.

How do I switch between Terraform workspaces?

To create a new workspace and switch to it, you can use terraform workspace new ; to switch workspaces you can use terraform workspace select ; etc. For example, creating a new workspace: $ terraform workspace new bar Created and switched to workspace "bar"! You're now on a new, empty workspace.


1 Answers

I suggest you take a look at the hashicorp best-practices repo, which has quite a nice setup for dealing with different environments (similar to what James Woolfenden suggested).

We're using a similar setup, and it works quite nicely. However, this best-practices repo assumes you're using Atlas, which we're not. We've created quite an elaborate Rakefile, which basically (going by the best-practices repo again) gets all the subfolders of /terraform/providers/aws, and exposes them as different builds using namespaces. So our rake -T output would list the following tasks:

us_east_1_prod:init us_east_1_prod:plan us_east_1_prod:apply  us_east_1_staging:init us_east_1_staging:plan us_east_1_staging:apply 

This separation prevents changes which might be exclusive to dev to accidentally affect (or worse, destroy) something in prod, as it's a different state file. It also allows testing a change in dev/staging before actually applying it to prod.

Also, I recently stumbled upon this little write up, which basically shows what might happen if you keep everything together: https://charity.wtf/2016/03/30/terraform-vpc-and-why-you-want-a-tfstate-file-per-env/

like image 72
Erik van Brakel Avatar answered Oct 04 '22 16:10

Erik van Brakel