Sobes.tech
Middle

When should Terraform modules be used?

sobes.tech AI

Answer from AI

Terraform modules should be used when:

  • Reusing configuration: Typical infrastructure components (networks, databases, K8s clusters) can be packaged into modules and reused across different projects or parts of a single project.
  • Abstracting complexity: Modules hide internal implementation details, providing a simple interface for use. This simplifies managing complex infrastructures.
  • Ensuring standardization: Modules allow defining configuration standards for specific resource types, ensuring uniform deployment.
  • Dividing responsibilities: Different teams can develop and maintain their modules responsible for specific parts of the infrastructure.
  • Improving readability and maintainability: Breaking down configuration into logical block-modules makes the code more readable and easier to support.
  • Accelerating deployment: Using ready-made, tested modules reduces the time needed to write new configurations.
  • Testing individual components: Modules enable testing specific parts of the infrastructure in isolation.

Examples of module usage:

// Using a module to create a VPC
module "vpc" {
  source = "./modules/vpc" // Path to local module or registry source
  region = "us-east-1"
  name   = "my-app-vpc"
  cidr_block = "10.0.0.0/16"
}

// Using a module to create a Kubernetes cluster
module "kubernetes_cluster" {
  source = "terraform-aws-modules/eks/aws" // Using a module from Terraform Registry
  version = "18.0.0"

  cluster_name = "my-eks-cluster"
  cluster_version = "1.21"
  vpc_id = module.vpc.vpc_id // Reference to output parameters of another module
  subnet_ids = module.vpc.public_subnets
}