Store terraform remote state file dynamic location in S3

785 views Asked by At

Basically, I have multiple running environments so when I try to upload the hard-code key address of terraform .tfstate state file it works perfectly but I wanna store my .tfstate file based on an environment variable or based on condition so I can differentiate between my dev-server or prod-server

my environments variable can be: dev, stage, or prod

The below code is just for a sample so get to know what I trying to do


variable "ENV" {
  default = "dev" # dev OR prod
}

provider "aws" {
  region     = "us-west-2"
}

terraform {
  backend "s3" {
    bucket          = "my-bucket-12345"
    key             = "proj/${var.ENV}/terraform.tfstate"
    region          = "us-west-2"
  }
}

resource "aws_instance" "example" {
  ami           = "ami-0d729a60"
  instance_type = "t2.micro"
}
1

There are 1 answers

0
Marcin On BEST ANSWER

You can't do this. You can't use variables in backend. The normal way to define TF configs for dev, stage, or prod is by using workspaces.