Search code examples
terraform

How to pass variables for Terraform S3 Backend resource?


terraform {
  backend "s3" {
    bucket = "mybucket"
    key    = "path/to/my/key"
    region = "us-east-1"
  }
}

Is it not possible to provide values for bucket and key above through variables file?

Because when I try doing the same like this:

terraform {
  backend "s3" {
    bucket = var.bucket
    key    = var.key
  }
}

, I get the following error:

Error: Variables not allowed

on main.tf line 3, in terraform:
3:      bucket = var.bucket

Variables may not be used here.

Error: Variables not allowed

on main.tf line 4, in terraform:
4:      key = key

Variables may not be used here.

Solution

  • Turns out we can't pass run-time values for backend bucket and key for storing state files.

    This is where the concept of Terraform Workspaces comes in!!