Fizg789Quax
Fizg789Quax

Reputation: 351

how to declare variables for s3 backend in terraform?

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?

Upvotes: 27

Views: 27632

Answers (4)

Montassar Bouajina
Montassar Bouajina

Reputation: 1652

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

Upvotes: 53

Mateusz Przybylek
Mateusz Przybylek

Reputation: 5905

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

  1. Create dev.tfbackend 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.tfbackend
    

Terrform Source

Upvotes: 17

Javier Carrillo
Javier Carrillo

Reputation: 1

I see that you're trying to use have different environments and specify them on your S3 config. But I'd recommend you to use workspaces.

To create a new workspace: terraform state new <name>

Upvotes: 0

user2599522
user2599522

Reputation: 3225

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

Upvotes: 2

Related Questions