Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform common variable usage in modules

Tags:

terraform

I am writing terraform script to create ASG on AWS. I tried to create it with terraform module to have a more reusable code. The problem is when I want to use variable from common-variable.tfvars on the module tf files, it keeps saying it is undefined and need to be declared. This way, the module will be less reuseable .

Here is an example

root
|
|___project 1
|     |_____ main.tf
|     |_____ common-variable.tfvars
|
|___ modules
      |
      |_____ a-module
                 |______ main.tf

So inside project 1 common-variable.tfvars, basically it looks like this

variable "a" { 
    description = "a variable"
    default = "a" 
}

variable "b" { 
    description = "a variable"
    default = "b" 
}

Inside a-module / main.tf looks like this

variable "name" {}

resource "aws_autoscaling_group" "asg-1" {
    name = "${var.a}"
    ...
}

When I do terraform init, it says

resource 'aws_autoscaling_group.asg-1' config: unknown variable 
referenced: 'a'. define it with 'variable' blocks

Any idea how i can use this common variable from within the module main .tf?


Update

I managed to pass terraform init by redeclaring the variable in each module. However, when i run terraform plan, this kind of error appears invalid value "common-variable.tfvars" for flag -var-file: multiple map declarations not supported for variables

like image 201
Reynaldi Wijaya Avatar asked Nov 23 '25 16:11

Reynaldi Wijaya


1 Answers

Wrong tfvars format, should be key / value only, such as:

a = "a"
b = "b"

Second, check how do you refer the module, should be something like this:

source = "../modules/a-module"
like image 62
BMW Avatar answered Nov 25 '25 11:11

BMW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!