Search code examples
terraformterraform-provider-aws

Terraform not passing variable to module


I'm trying to pass a variable from an environment dir to a module, but having some issues. My directory structure looks like this

repository
 -> prod
 -> test
      main.tf 
      terraform.tf
      vars.tfvars
 -> modules
     infra
       main.tf
       terraform.tf

In test/main.tf I have

terraform {
  required_providers {
    aws = {
      source = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
}

provider "aws" {
  region = "eu-west-1"
}

module "launch" {
  source = "../../modules/infra"
  range = var.range
}

test/terraform.tf looks like this

variable "range" {}

test/vars.tfvars

range="10.0.0.0/16"

modules/infra/main.tf

resource "aws_vpc" "testvpc" {
  cidr_block = var.range
}

When I run this I get the prompt

var.range
  Enter a value:

I'm expecting it to pick up the value from the variable automatically, but even when I do enter the value I get the error

│ Error: Unsupported argument
on main.tf line 20, in module "launch":
range = var.range 
An argument named "range" is not expected here

Is it possible to pass a variable from a file for a given environment to a module?


Solution

  • Make sure the file modules/infra/terraform.tf contains the variable:

    variable "range" {}