Bird
Raised Fist0
Terraformcloud~5 mins

Dependency inversion with modules in Terraform - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
When building infrastructure with Terraform, you often want to reuse code and keep your setup organized. Dependency inversion with modules helps by letting you create small reusable pieces that depend on abstract inputs rather than concrete details. This makes your infrastructure easier to manage and change.
When you want to reuse the same infrastructure setup in different environments like development and production.
When you need to change parts of your infrastructure without rewriting the whole setup.
When you want to share common infrastructure code across multiple projects.
When you want to clearly separate responsibilities in your infrastructure code.
When you want to avoid tight coupling between different parts of your infrastructure.
Config File - main.tf
main.tf
terraform {
  required_version = ">= 1.0"
}

module "network" {
  source = "./modules/network"
  cidr_block = "10.0.0.0/16"
}

module "web_server" {
  source = "./modules/web_server"
  subnet_id = module.network.subnet_id
}

This main Terraform file uses two modules: network and web_server. The network module creates a network with a CIDR block. The web_server module depends on the network module by receiving the subnet ID as input. This shows dependency inversion because the web server module does not create the network itself but depends on the network module's output.

Commands
This command initializes the Terraform working directory. It downloads the modules and sets up the backend to manage state.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure. All Terraform commands should now work.
This command shows what Terraform will do when applying the configuration. It helps verify that the modules and their dependencies are set up correctly.
Terminal
terraform plan
Expected OutputExpected
Refreshing Terraform state in-memory prior to plan... An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # module.network.aws_vpc.main will be created + resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" + id = (known after apply) } # module.web_server.aws_subnet.main will be created + resource "aws_subnet" "main" { + vpc_id = (known after apply) + id = (known after apply) } Plan: 2 to add, 0 to change, 0 to destroy.
This command applies the planned changes and creates the infrastructure. The -auto-approve flag skips manual confirmation.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_vpc.main: Creating... aws_vpc.main: Creation complete after 3s [id=vpc-12345678] aws_subnet.main: Creating... aws_subnet.main: Creation complete after 2s [id=subnet-87654321] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
-auto-approve - Automatically approve the apply without asking for confirmation
This command shows the subnet ID output from the network module, proving the dependency inversion works by passing this value to the web server module.
Terminal
terraform output subnet_id
Expected OutputExpected
subnet-87654321
Key Concept

If you remember nothing else from this pattern, remember: modules should depend on inputs and outputs, not on each other's internal details.

Common Mistakes
Hardcoding resource IDs inside modules instead of passing them as inputs.
This creates tight coupling and makes modules less reusable and harder to maintain.
Pass resource IDs and other dependencies as input variables to modules.
Not defining outputs in modules to share important values.
Without outputs, other modules cannot receive necessary information, breaking dependencies.
Define outputs in modules for any values that other modules need.
Calling resources directly across modules instead of using outputs and inputs.
Terraform modules are isolated; direct resource references across modules cause errors.
Use module outputs and input variables to connect modules.
Summary
Initialize Terraform to download modules and set up the environment.
Use terraform plan to preview changes and verify module dependencies.
Apply the configuration to create resources with terraform apply.
Use terraform output to check values passed between modules.

Practice

(1/5)
1. What does dependency inversion mean in Terraform modules?
easy
A. Modules cannot accept variables
B. Modules depend on inputs instead of creating resources themselves
C. Modules always create all resources internally
D. Modules must be written in the root configuration

Solution

  1. Step 1: Understand module dependency principle

    Dependency inversion means modules should not create resources directly but rely on inputs.
  2. Step 2: Identify correct description

    Modules depend on inputs instead of creating resources themselves correctly states modules depend on inputs, making them flexible and reusable.
  3. Final Answer:

    Modules depend on inputs instead of creating resources themselves -> Option B
  4. Quick Check:

    Dependency inversion = Modules use inputs [OK]
Hint: Modules get resource info via inputs, not by creating resources [OK]
Common Mistakes:
  • Thinking modules must create all resources internally
  • Assuming modules cannot accept variables
  • Believing modules must be in root config
2. Which of the following is the correct way to pass a resource ID to a module in Terraform?
easy
A. module "example" { resource_id = aws_instance.example.id }
B. module "example" { input_id = aws_instance.example.id }
C. module "example" { instance_id = var.instance_id }
D. module "example" { instance_id = aws_instance.example.id }

Solution

  1. Step 1: Identify correct variable passing syntax

    Modules accept variables by name; the value can be a resource attribute like aws_instance.example.id.
  2. Step 2: Check option correctness

    module "example" { instance_id = aws_instance.example.id } correctly passes instance_id with the resource ID aws_instance.example.id.
  3. Final Answer:

    module "example" { instance_id = aws_instance.example.id } -> Option D
  4. Quick Check:

    Pass resource ID as variable = module "example" { instance_id = aws_instance.example.id } [OK]
Hint: Use variable name = resource.attribute to pass IDs [OK]
Common Mistakes:
  • Using undefined variable names like resource_id or input_id
  • Passing resource IDs without variable names
  • Confusing variable and resource references
3. Given this Terraform root module snippet:
resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

module "network" {
  source = "./modules/network"
  vpc_id = aws_vpc.main.id
}

What is the expected behavior of the network module?
medium
A. It ignores the VPC ID and creates a subnet only
B. It creates a new VPC inside the module
C. It uses the existing VPC ID passed as input
D. It fails because VPC ID cannot be passed as input

Solution

  1. Step 1: Analyze root module resource and module call

    The root module creates an aws_vpc resource and passes its ID to the network module as vpc_id.
  2. Step 2: Understand module behavior with input

    The network module uses the passed vpc_id to configure resources inside that VPC, not create a new one.
  3. Final Answer:

    It uses the existing VPC ID passed as input -> Option C
  4. Quick Check:

    Module uses input vpc_id = It uses the existing VPC ID passed as input [OK]
Hint: Modules use passed IDs to link resources, not recreate them [OK]
Common Mistakes:
  • Assuming module creates a new VPC ignoring input
  • Thinking passing resource IDs is invalid
  • Believing module fails without explicit VPC creation
4. You have this module call:
module "db" {
  source = "./modules/db"
  subnet_id = aws_subnet.app.id
}

Inside the module, the variable is declared as variable "subnet" { type = string }. What error will occur?
medium
A. Error: Unknown variable 'subnet_id' in module
B. Error: Variable 'subnet' not provided
C. No error, variable names can differ
D. Error: aws_subnet.app.id is invalid

Solution

  1. Step 1: Compare variable name and input argument

    The module expects a variable named 'subnet' but the input is 'subnet_id'.
  2. Step 2: Understand Terraform variable matching

    Terraform matches input arguments to variable names exactly. 'subnet_id' does not match any variable, causing an unsupported argument error.
  3. Final Answer:

    Error: Unknown variable 'subnet_id' in module -> Option A
  4. Quick Check:

    Variable name mismatch causes unknown variable error [OK]
Hint: Variable names must match exactly between module and call [OK]
Common Mistakes:
  • Assuming variable names can differ
  • Confusing variable name with resource attribute name
  • Ignoring error messages about missing variables
5. You want to create a reusable module for an AWS security group that attaches to any VPC. Which approach follows dependency inversion best?
hard
A. Module accepts a VPC ID as input and creates security group in that VPC
B. Module hardcodes a VPC ID inside the module code
C. Module requires the user to create security group outside and passes its ID
D. Module creates its own VPC and security group inside

Solution

  1. Step 1: Understand dependency inversion for modules

    Modules should not create dependent resources like VPCs but accept them as inputs.
  2. Step 2: Evaluate options for best practice

    Module accepts a VPC ID as input and creates security group in that VPC accepts VPC ID as input and creates the security group inside that VPC, following dependency inversion.
  3. Final Answer:

    Module accepts a VPC ID as input and creates security group in that VPC -> Option A
  4. Quick Check:

    Pass dependencies as inputs for flexibility [OK]
Hint: Pass VPC ID as input; module creates resources inside it [OK]
Common Mistakes:
  • Hardcoding resource IDs inside modules
  • Modules creating dependent resources themselves
  • Requiring users to create resources outside without module help