RousselTMLEARNING

Automation

Terraform modules: designing, versioning and reusing

Structure Terraform with modules: root module and child modules, inputs and outputs, sources (local, Git, registry), versioning, composition, design best practices and module registry.

1. Principle #

Reusable building blocks.

Structure #

Module composition
A module = a folder with variables.tf, main.tf, outputs.tf and a README.
module "reseau" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"
  name    = "prod"
  cidr    = "10.0.0.0/16"
  azs             = ["eu-west-3a", "eu-west-3b"]
  private_subnets = ["10.0.11.0/24", "10.0.12.0/24"]
  public_subnets  = ["10.0.1.0/24", "10.0.2.0/24"]
}

module "app" {
  source     = "./modules/app"
  subnet_ids = module.reseau.private_subnets
}

2. Sources and versions #

Where modules come from.

Sources #

SourceExample
Local folder./modules/app
Public registryterraform-aws-modules/vpc/aws + version
Gitgit::https://git.exemple.fr/modules/app.git?ref=v1.4.0
Private registryapp.terraform.io/acme/app/aws

Rule #

Good practice: Always pin a version (or a Git tag): a module that changes under your feet makes plans unpredictable.

3. Designing well #

Useful modules.

Rules #

  • One module = one responsibility (network, database, application), not a mere wrapper around a resource.
  • Typed, documented variables, with validations and safe defaults.
  • Outputs for everything other modules need.
  • Examples and tests (terraform test) in the module repository.
  • Semantic versioning and a changelog.

Related articles

Terraform: principles, architecture and workflow

Understand Terraform: declarative infrastructure as code, architecture (core, providers, state), the init, pl…

The HCL language: resources, variables, outputs, data and expressions

Writing Terraform: terraform, provider, resource and data blocks, typed variables with validation, locals, ou…

Terraform state: remote backends, locking, import and refactoring

Manage Terraform state: the role of the state file, sensitive data, remote backends (S3, azurerm, gcs, HCP Te…

Keep learning

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!