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" {}
...
}
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
- 1 - Start : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-1-1ko7
- 2 - Definitions : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-2-definitions-93p
- 3 - Simple database : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-3-simple-database-a9o
- 4 - HA Database : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-4-ha-database-4kek
- 5 - DR database : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-5-dr-database-278b
- 6 - Create from snapshot : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-6-create-from-snapshot-2mbf
- 7 - Dynamic Terraform backend definition : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-7-dynamic-terraform-backend-definition-3aga
- 8 - Multiple instances in multiple regions : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-8-multiple-instances-in-multiple-regions-210d
- 9 - Generate a random value : https://dev.to/adaendra/how-to-setup-a-hadr-database-in-aws-9-generate-a-random-value-5g8a
Top comments (0)