Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform - How to use tfvars with modules

Tags:

terraform

With three different environments, I want to be able to dynamically set variables based on the environment. In my example below, let's say the instance type is different between dev and prod. I'm not able to reference instance_type within the module UNLESS I have a vars.tf file alongside my terraform.tfvars.

The error I get is:

unknown variable referenced: 'instance_type'. define it with 'variable' blocks

If that's the case, then wouldn't this file be the same exact file under modules/apollo/vars.tf?

I thought modules/apollo/vars.tf defines the necessary variables needed for the module. I didn't think it was necessary within the "root" level under env-dev/services/apollo/. If there's a "better" way of doing this, I'm all ears.

├── env-dev
│   └── services
│       └── apollo
│           ├── main.tf
│           ├── terraform.tfvars    
│           └── vars.tf # Do i need this?
├── env-test
├── global
├── mgmt
└── modules
    ├── apollo
    │   ├── main.tf
    │   ├── user_data.tpl
    │   └── vars.tf
    └── defaults
        └── main.tf

env-dev/services/apollo/terraform.tfvars

instance_type    = "t2.medium"

env-prod/services/apollo/terraform.tfvars

instance_type    = "t2.large"

modules/apollo/vars.tf

variable "instance_type" {
  description = "EC2 Instance Type"
}

modules/apollo/main.tf

resource "aws_instance" "instance" {     
  ...
  instance_type           = "${var.instance_type}"
  ...
}
like image 225
sdot257 Avatar asked Oct 10 '17 02:10

sdot257


1 Answers

Adjust the structure, this is my understand for your applications.

├── dev
│   └── apollo_terraform.tfvars    
├── test
│   └── apollo_terraform.tfvars
├── global
│   └── apollo_terraform.tfvars
├── mgmt
│   └── apollo_terraform.tfvars
├── main.tf,  vars.tf, output.tf, apollo.tf, default.tf, etc
└── modules
    ├── apollo
    │   ├── main.tf
    │   ├── user_data.tpl
    │   └── vars.tf
    └── defaults
        └── main.tf

apollo.tf will have source module code to use the share module apollo. Same setting for default.tf

your plan/apply command should be like this:

terraform plan -var-file=${env}/apollo_terraform.tfvars
like image 91
BMW Avatar answered Sep 20 '22 20:09

BMW