how to declare variables for s3 backend in terraform?

Viewed 8726

s3.tf

terraform {
backend "s3" {
bucket = "some-bucket"
key = "path/to/key"
region = "some-aws-region" 
}}

How to pass the bucket and region values to this from a variables.tf file?

3 Answers

hello here's a solution :

terraform {
  backend "s3" {
  }
}

pass the backend like that and then :

on the terraform init command :

terraform init \
-backend-config="bucket=${TFSTATE_BUCKET}" \
-backend-config="key=${TFSTATE_KEY}" \
-backend-config="region=${TFSTATE_REGION}" 

you should use env to set TFSTATE_BUCKET TFSTATE_KEY and TFSTATE_REGION

here's a link of the docs : the Terraform docs on "Partial Configuration" of Backends

Montassar's answer is quite good, but I prefer file version:

  1. Create dev.conf file
    bucket="some-bucket"
    region="some-aws-region"
    
  2. Remove those properties in main.tf,
    terraform {
     backend "s3" {
      key = "path/to/key"
    }}
    
  3. Run init:
    terraform init -backend-config=dev.conf
    

Terrform Source

I believe this is not currently possible as if you add a variable interpolation in that, you will get an error

terraform.backend: configuration cannot contain interpolations

Related