DEV Community

Cover image for How-to setup a HA/DR database in AWS? [7 - Dynamic Terraform backend definition]
Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

How-to setup a HA/DR database in AWS? [7 - Dynamic Terraform backend definition]

In this post we will see something which can be really useful to use the same script in multiple environment or for multiple projects without modifying the code!


To do this magic trick, we will define dynamically the backend that we will use to store the terraform state.

Backend declaration

First, we need to declare in the script which kind of backend we want to use.

In our example, it will be with AWS S3.

terraform {
  ...
  backend "s3" {}
  ...
}
Enter fullscreen mode Exit fullscreen mode

Dynamic magic

So to have a dynamic backend definition, you have to add declare some parameters as options of the terraform init command.

Backend parameters

  • bucket : Name of the S3 bucket where you want to store the Terraform state.
  • key : Path of the Terraform state file in the S3 bucket. Generally it is this parameter who will be updated to ensure you that each terraform state is located in a different place.
  • region : Region where the bucket is
  • encrypt : A boolean to know if you want to encrypt the file (if you have a doubt, set it to true)

Command option

To give the backend parameters, you have to way to do it :

  • declare a parameter with a key=value

-backend-config='bucket=test'

  • declare a tfvars file which contains some/all the configurations

-backend-config='configs/configs_backend.tfvars'


Then you just have to give the right parameters when using the terraform commands, and you will be able to define multiple infra with one script!


I hope it will help you! 🍺

And see you soon for the next part of this serie. 😀


Serie link


You want to support me?

Buy Me A Coffee

Top comments (0)