0
votes

I have a project that provisions the infrastructure in AWS using terraform. We have different environments dev, stg, prod and the way we deploy to each of these environments is through environment specific .tfvars . This is our structure

infra-project
    |_____Module1
    |        Main.tf
             Variables.tf
             output.tf
             Environments
               | 
               | _____ dev
                        |_____ terraform.tfvars
               | 
               | _____ stg
                        |_____ terraform.tfvars

               | 
               | _____ prod
                        |_____ terraform.tfvars

Sample content of the terraform.tfvars file in dev

region = "us-west-2"
ami_id = "ami-0234er2455665"
subnet_id = "subnet-345rf789d"
instanceType = "t2.micro"
pvtIP= "10.12.0.0/16"

The environments are going to grow and it is not desirable to create environment specific terraform.tfvars everytime. Is there a way to automate generating the tfvars for each environment so that it can be deployed to n environments without altering the project structure everytime?

1
well, each environment is different. That's why you separate them. You can automate generating the tfvars elsewhere within CI/CD workflows or beyond with a pre-defined template but you have to pass some data to resolve that template. You may find a few common fields and make them redundant but can't automate it completely.harshavmb

1 Answers

0
votes

I think you do need to create an environment specific file each time. They need to be declared somewhere. They really cannot be Auto generated without the base declarations anyway..

I would remove the Environment folder and used named tfvars files for each environment.

Example:

terraform apply -var-file="dev.tfvars"

Just add a new tfvars file free each supported environment.