4

How do I manage remote state for different environments? I originally wanted to use variables in my remote state definations but realized I cannot use variables like:

provider "aws" {
  region = "ap-southeast-1"
}

terraform {
  backend "s3" {
    bucket = "${var.state_bucket}"
    key = "${var.state_key}"
    region = "ap-southeast-1"
  }
}

data "terraform_remote_state" "s3_state" {
  backend = "s3"
  config {
    bucket = "${var.state_bucket}"
    key = "${var.state_key}"
    region = "ap-southeast-1"
  }
}

But realised I cannot use variables in this case? I can hardcode the bucket name but the bucket may not be the same across environments

Jiew Meng
  • 84,767
  • 185
  • 495
  • 805
  • Possible duplicate of [Terraform terraform\_remote\_state Partial Configuration](https://stackoverflow.com/questions/45684460/terraform-terraform-remote-state-partial-configuration) – ydaetskcoR Jan 22 '19 at 11:56
  • Based on the suggested duplicate and the question above, is it possible to supply `data` for the `key` and `bucket`? https://www.terraform.io/docs/providers/terraform/d/remote_state.html#attributes-reference – Matthew Schuchard Jan 22 '19 at 14:02

1 Answers1

0

You will want to use what Terraform calls workspaces. Here is the documentation: https://www.terraform.io/docs/state/workspaces.html

So way you have a piece of state called: MyStateKey

When you use workspaces it will append the workspace name to the end of the existing key. For example if you created a workspace called "dev" then the key in the remote state would be "MyStateKey:dev".

I would suggest you use some conventions to make it easier like using the "default" workspace as production, with additional workspaces named after your other environments. Then when you run terraform you can set the workspace or use the TF_WORKSPACE environment variable to set it.

Jamie
  • 3,094
  • 1
  • 18
  • 28
  • 3
    We have a convention that ensures `default` is never used, basically there's a resource that checks the `terraform.workspace` is not "default", otherwise it halts. The idea being it's better to be explicit about which environment you're targeting. – bluescores Jan 22 '19 at 15:36