Filters
How to search
  • Plain words find names, texts and examples.
  • "two words" finds the exact phrase.
  • --name or -x finds an option.
  • #word looks only inside commands.
  • @grep finds lessons and labs that use grep.
  • Filters: cat:network · in:labs · in:notes · level:rhcsa · ch:8 · root:yes. Put ! before a word to leave it out. OR between words means one of them.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search

Chapter 8Name in the course: Objective 5: Terraform modules

Reuse code with modules

A module is a folder of Terraform files used as one building block: "a network", "a web server", "a database". Every configuration is already a module (the root module); it can call child modules from local folders, Git or a registry.

  • 5 Lessons
  • 2 Commands

$ run as a normal user# run as root (or with sudo)

Skills in this chapter

  • Use and version modules

8.1

Know where modules come from

The source argument tells Terraform where to get the module.

8.2

Call a module

A module block gives the module's input variables and reads its outputs.

main.tf
module "network" {
  source        = "./modules/network"
  name          = "vnet-shop-${var.env}"
  address_space = ["10.30.0.0/16"]
  subnets = {
    web = "10.30.1.0/24"
    app = "10.30.2.0/24"
  }
  tags = local.tags
}
 
resource "azurerm_network_interface" "web" {
  # ...
  ip_configuration {
    name                          = "ipconfig1"
    subnet_id                     = module.network.subnet_ids["web"]
    private_ip_address_allocation = "Dynamic"
  }
}

8.3

Write a module

A good module has a clear interface: variables.tf (inputs), main.tf (resources), outputs.tf (results), versions.tf (providers), and a README.

modules/network/outputs.tf
output "vnet_id" {
  value = azurerm_virtual_network.this.id
}
 
output "subnet_ids" {
  value = { for k, s in azurerm_subnet.this : k => s.id }
}

8.4

Understand variable scope

A module sees only its own variables and locals. It can not read var. of the caller. Everything must be passed in as inputs, and comes back only through outputs.

FromToHow
Root moduleChild moduleModule arguments (name = …)
Child moduleRoot modulemodule.NAME.OUTPUT
Child AChild BThrough the root: module.a.x as input of module "b"

Exam tip

Resources inside a module are addressed as module.network.azurerm_virtual_network.this in state commands.

8.5

Pin module versions

Registry modules use version; Git modules use ?ref=TAG. Pin them, and upgrade on purpose.

main.tf
module "vnet" {
  source  = "Azure/avm-res-network-virtualnetwork/azurerm"
  version = "~> 0.8"
  # ...
}
terraform init -upgrade

Remember

version works only for registry modules. For Git sources, the version is in the URL (?ref=v1.2.0).

At work

Review public modules before you use them: read the code, the open issues and how often it is updated. A module runs with the rights of your pipeline.

All commands in this chapter