Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Infrastructure as Code FAQ: Top Questions

4. What are Terraform modules and how do they help in IaC?

Terraform modules are containers for multiple resources that are used together. A module encapsulates a group of related resources and allows them to be reused across different parts of a configuration or across different projects, improving organization, scalability, and maintainability.

πŸ—ΊοΈ Step-by-Step Instructions:

  1. Create a directory for your module (e.g., modules/s3_bucket).
  2. Inside the module directory, define the infrastructure resources (e.g., main.tf, variables.tf, outputs.tf).
  3. Reference the module in your main configuration using the module block.
  4. Pass input variables and use outputs as needed.

πŸ“₯ Example Input:

# modules/s3_bucket/main.tf
resource "aws_s3_bucket" "this" {
  bucket = var.bucket_name
  acl    = "private"
}

# modules/s3_bucket/variables.tf
variable "bucket_name" {
  type = string
}

# main.tf
module "my_bucket" {
  source      = "./modules/s3_bucket"
  bucket_name = "my-module-bucket"
}

πŸ† Expected Output:

A reusable S3 bucket is provisioned using the module with a specified name.

βœ… Terraform Module Commands:

terraform init
terraform get
terraform plan
terraform apply

πŸ“˜ Detailed Explanation:

  • Encapsulation: Modules wrap resources for reuse and abstraction.
  • Reusability: Same module can be used across different environments or services.
  • Versioning: Modules can be version-controlled and published in registries.
  • Composition: Complex infrastructure can be broken down into smaller logical modules.

πŸ› οΈ Use Cases:

  • Standardizing infrastructure components like VPCs, IAM roles, S3 buckets, etc.
  • DRY principle: Reduce duplication across Terraform configurations.
  • Ease of testing and debugging isolated components.
  • Sharing best practices through public or internal Terraform registries.