Modules Using a Sub Module

We will learn how to use a module within the module.

Submodules

Modules can use modules inside themselves. We are going to go through an example of a three-way cross-talk module. The purpose of this module is to set up ingress and egress on a protocol and port of your choosing between three AWS security groups in both directions. To do this by hand would require twelve security group rules, but this can be shortened by using modules.

Project example

Let’s dive straight into the example. If you are following along with the course, create a folder in your workspace and add the following file structure:

Press + to interact
cross-talk/
main.tf
variables.tf
cross-talk-3-way/
main.tf
variables.tf
main.tf

Cross-talk folder

Press + to interact
main.tf
variables.tf
resource "aws_security_group_rule" "first_egress" {
from_port = var.port
to_port = var.port
protocol = var.protocol
security_group_id = var.security_group_1.id
type = "egress"
source_security_group_id = var.security_group_2.id
}
resource "aws_security_group_rule" "first_ingress" {
from_port = var.port
to_port = var.port
protocol = var.protocol
security_group_id = var.security_group_1.id
type = "ingress"
source_security_group_id = var.security_group_2.id
}
resource "aws_security_group_rule" "second_egress" {
from_port = var.port
to_port = var.port
protocol = var.protocol
security_group_id = var.security_group_2.id
type = "egress"
source_security_group_id = var.security_group_1.id
}
resource "aws_security_group_rule" "second_ingress" {
from_port = var.port
to_port = var.port
protocol = var.protocol
security_group_id = var.security_group_2.id
type = "ingress"
source_security_group_id = var.security_group_1.id
}

Let’s pause and discuss the cross-talk module that we have just defined.

variables.tf

Looking at the variables.tf, we have introduced a couple of new concepts. The first is that we are taking the whole ...