1
votes

I am building a VPC and AWS EC2 with two modules. One for VPC and one for EC2. I am struggling to figure out how to use output for the subnets to use in the ec2 module.

I created the subnets in the VPC module.

    resource "aws_subnet" "tnt_public_subnets_cidr" {
    vpc_id                  = aws_vpc.tnt_vpc.id
    count             = length(var.availability_zones)
    cidr_block        = var.tnt_public_subnets_cidr [count.index]
    availability_zone = element(var.availability_zones, count.index)
    map_public_ip_on_launch = true
    tags ={
       Name = "${var.environment}_mgmt_subnet_${count.index + 1}"
       Environment = var.environment
    }
}

then I used an output.

    output "tnt_public_subnets_cidr"{
    value = [aws_subnet.tnt_public_subnets_cidr.*.id]
    }

Then inside the ec2 module I create a variable.

    variable "tnt_public_subnets_cidr"{
    }

Now what do I do? Where do I use this in the ec2 module main? subnet_id?

   resource "aws_instance" "Webserver" {
   count                       = var.instance_count
   ami                         = var.ami
   instance_type               = var.instance_type
   associate_public_ip_address = var.public_address
   disable_api_termination     = true
   subnet_id                   = var.tnt_public_subnets_cidr

Then in the root module.

   module "webserver" {
   source      = "./modules/ec2/webserver"
   ami         = var.ami_value
   count       = var.count
   environment = var.environment
   subnet_id   = module.vpc.tnt_public_subnets_cidr.id
   }

When I try to run a terraform plan I get this error:

    Error: Missing required argument

    on main.tf line 15, in module "webserver":
    15: module "webserver" {

    The argument "tnt_public_subnets_cidr" is required, but no definition was
    found.

So where am I going wrong? I struggle with how outputs flow when using them for other modules.

1
How did it go? Still unclear what you can do? - Marcin

1 Answers

1
votes

In your module you have a variable without a default value:

   variable "tnt_public_subnets_cidr"{
    }

This means that you must provide it when you instantiate your module:

   module "webserver" {
   source      = "./modules/ec2/webserver"
   ami         = var.ami_value
   count       = var.count
   environment = var.environment
   tnt_public_subnets_cidr = module.vpc.tnt_public_subnets_cidr.id
   }

Your output should also be a list, not a list of lists:

output "tnt_public_subnets_cidr"{
    value = aws_subnet.tnt_public_subnets_cidr.*.id
}