Tips and Tricks #145: Use Terraform Modules for Reusable Infrastructure

Create reusable infrastructure components with Terraform modules for consistency and DRY code.

Code Snippet

# modules/api-gateway/main.tf
variable "name" {
  type = string
}

variable "lambda_arn" {
  type = string
}

resource "aws_apigatewayv2_api" "this" {
  name          = var.name
  protocol_type = "HTTP"
}

resource "aws_apigatewayv2_integration" "this" {
  api_id             = aws_apigatewayv2_api.this.id
  integration_type   = "AWS_PROXY"
  integration_uri    = var.lambda_arn
}

output "api_endpoint" {
  value = aws_apigatewayv2_api.this.api_endpoint
}

# Usage in main.tf
module "user_api" {
  source     = "./modules/api-gateway"
  name       = "user-api"
  lambda_arn = aws_lambda_function.users.arn
}

Why This Helps

  • Consistent infrastructure across environments
  • Reduces code duplication by 70%+
  • Easier to maintain and update

How to Test

  • terraform plan to verify changes
  • Deploy to staging environment first

When to Use

Any repeated infrastructure pattern. API gateways, databases, networking, etc.

Performance/Security Notes

Version your modules. Use terraform-docs to generate documentation automatically.

References


Try this tip in your next project and share your results in the comments!


Discover more from Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.