Reputation: 1008
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.
Upvotes: 13
Views: 14435
Reputation: 13860
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 init
command:
terraform init -backend-config=backend.tfvars
You need a separate backend config file instead of your usual tfvars file because 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.
In July 2024, OpenTofu (a Terraform fork), allows variables and locals for backends.
Upvotes: 17
Reputation: 1008
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!!
Upvotes: 0