How to pass variables for Terraform S3 Backend resource?

Viewed 3709
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.
2 Answers

Create a file named backend.tfvars with content:

bucket = "mybucket"
key    = "path/to/my/key"

Specify this file name in a command line option to the terraform command:

terraform init -backend-config=backend.tfvars

The reason you need to use a separate backend config file instead of your usual tfvars file is that these values are used when you set up your backend. That means they need to be provided when you run terraform init, not later when you use the backend with commands like terraform apply.

See the terraform documentation on partial configuration for more details.

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!!

Related