Module composition (aka using output of one module as input for another module) not working

Hi all,

Terraform prompts me to enter a value for variables which i have already declared using the module... Idea is to use the output id of the created subnet as an input to spawn an ec2. I only included parts that are relevant

directory format is as follows

main.tf
variables.tf
/-modules
/-- vpc
---main.tf
---output.tf
---variables.tf
/--ec2
---main.tf
---output.tf
---variables.tf

in main.tf

module "vpc" {
  source = "./modules/vpc"
  aws_vpc_id = var.aws_vpc_id
  subnet_cidr_block_range = var.subnet_cidr_block_range
}

module "ec2" {
  source = "./modules/ec2"
  ec2_subnet_id = "${module.vpc.aws_subnet_id}"
}

in variables.tf

variable "ec2_subnet_id" {
  type = string
  description = "id of subnet to spawn ec2 in"
}

variable "aws_vpc_id" {
  type = string
  description = "created VPC id"
}

variable "subnet_cidr_block_range" {
  type = string
  description = "Cidr block range of subnet"
}

in vpc/main.tf

resource "aws_subnet" "subnet-main" {
  vpc_id = var.aws_vpc_id
  cidr_block = var.subnet_cidr_block_range
}

in vpc/outputs.tf

output "aws_subnet_id" {
  value = "${aws_subnet.subnet-main.id}"
}

in ec2/main.tf

resource "aws_instance" "ec2-instance" {
  subnet_id = var.ec2_subnet_id
}

in ec2/variables.tf

variable "ec2_subnet_id" {
  type = string
  description = "id of subnet to spawn ec2 in"
}

Hi @greendizze,

In your root variables.tf you’ve shown three variable declarations. Because those are in the root module, they must be set as plan options (on the command line, or via the interactive prompts, etc) whenever you run terraform plan or terraform apply.

If you want to be able to run Terraform without providing values for those variables, you can remove those declarations from your variables.tf file. You will then need to change how you populate the corresponding arguments inside the module "vpc" and module "ec2" blocks, so that those values come either from hard-coded values or from another module, depending on your needs.