Top 10 Terraform Modules You Should Know

Infrastructure as Code (IaC) is the backbone of modern DevOps, and Terraform is the go-to tool for managing cloud infrastructure efficiently. But writing infrastructure code from scratch for every project isn’t scalable. That’s where Terraform modules come in.

Terraform Module allows you to reuse and share configurations across environments and teams. In this blog, we’ll explore the Top 10 Terraform modules that every DevOps engineer should have in their toolkit.

1. AWS VPC Terrafom Module

The VPC (Virtual Private Cloud) is the core building block of any AWS infrastructure. It acts like a private network in the cloud where you can launch and manage AWS resources such as EC2, RDS, Lambda, etc.

Creating a production-ready VPC manually can be a complex and time-consuming process. That’s where the Terraform AWS VPC Module comes in. This Terraform module helps you automate the creation of a highly configurable, secure, and scalable Virtual Private Cloud (VPC) with minimal code.

The terraform-aws-vpc module can provision:

  • Custom IPv4 CIDR blocks for your VPC
  • Multiple public and private subnets
  • NAT Gateways for internet access from private subnets
  • Internet Gateways for public subnets
  • Route tables for traffic control
  • Elastic IPs, DHCP options, and DNS support
  • VPC Flow Logs for traffic monitoring

Here are a few reasons why DevOps engineers like using this module:

When it comes to cloud infrastructure, DevOps engineers value tools that save time, reduce complexity, and promote reliability, and that’s exactly what this VPC Terraform module delivers. Here’s why it’s a favorite in the DevOps community:

Production-Ready in Minutes

Setting up a secure and scalable VPC from scratch can take hundreds of lines of Terraform code and a lot of trial and error. This module simplifies that process by offering predefined configurations that just work. With a few lines of input, you get a fully-functional VPC complete with subnets, routing, NAT gateways, and more, ready for production or development environments

Highly Customizable

No two cloud architectures are the same, and this Terraform module understands that. It provides dozens of input variables to help you tailor the VPC exactly to your needs. If you want 3 public subnets and 6 private ones? Prefer to use your own CIDR blocks? Need DNS support or to turn NAT gateways on/off?

You can easily adjust settings like:

  • Subnet CIDR ranges
  • Number of subnets per Availability Zone
  • NAT gateway configurations
  • DHCP options, DNS settings, and more

This flexibility makes it perfect for both small projects and complex enterprise architectures.

Best Practices Built-In

Security and scalability are top priorities in cloud infrastructure. This Terraform module incorporates AWS-recommended networking and security best practices right out of the box. That includes:

  • Splitting traffic between public and private subnets
  • Enabling secure outbound internet access via NAT Gateways
  • Optional VPC Flow Logs for network visibility
  • Default tagging and naming conventions to maintain resource clarity

So even if you’re new to AWS networking, you can rest easy knowing your VPC setup is aligned with industry standards.

Community-Tested and Trusted

This Terraform module is part of the widely respected terraform-aws-modules GitHub organization. It has:

  • Thousands of GitHub stars
  • Active maintenance from experienced cloud engineers
  • Extensive documentation
  • Support for new AWS features and Terraform releases

It’s also used by thousands of DevOps professionals worldwide, which means any bugs get caught and fixed quickly, and you benefit from a mature, battle-tested solution.

Here’s a simple example of how to use this Terraform module to create a basic VPC:

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.1.0"

  name = "my-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["us-east-1a", "us-east-1b", "us-east-1c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = true
  enable_dns_hostnames = true
  enable_dns_support   = true

  tags = {
    Environment = "dev"
    Terraform   = "true"
  }
}
  • We define a VPC with a /16 CIDR block.
  • It includes 3 public and 3 private subnets across multiple Availability Zones.
  • A single NAT Gateway allows outbound internet access from private subnets.
  • DNS support is enabled for name resolution within the VPC.

Security Best Practices

  • Use private subnets for sensitive workloads.
  • Enable VPC Flow Logs to monitor and troubleshoot network traffic.
  • Use Network ACLs and Security Groups to restrict access.

It’s also available on the Terraform Registry:

Terraform Registry – VPC Module

2. EC2 Instance Terraform Module

This module is used to launch and manage EC2 instances in AWS using Terraform. Whether you’re setting up a single server or managing multiple instances, this Terraform module helps simplify the process.

Managing EC2 instances manually can be time-consuming and error-prone, especially when you’re dealing with multiple configurations, environments, or regions. The “terraform-aws-ec2-instance” module is a reusable and well-maintained module that lets you quickly spin up EC2 instances with customizable options, without writing a huge amount of Terraform code.

With this Terraform module, you can:

  • Easily define instance settings like AMI ID, instance type, key pair, and availability zone.
  • Attach security groups and network interfaces to control traffic in and out.
  • Tag your resources for better organization and cost tracking.
  • Automatically attach EBS volumes and configure storage for each instance.
  • Use user-data scripts to bootstrap your instances with the required software or configuration during launch.
  • Enable detailed monitoring and instance termination protection with just a few flags.

This module is great for DevOps engineers and infrastructure teams who want to automate EC2 provisioning, reduce human errors, and manage infrastructure as code with best practices.

This Terraform module follows best practices and is maintained by the community at terraform-aws-modules/terraform-aws-ec2-instance. It’s a production-grade Terraform module used by thousands of teams around the world.

Here’s how easy it is to use the EC2 module in your Terraform configuration:

module "ec2_instance" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "~> 5.0"

  name           = "dev-web-server"
  instance_count = 1

  ami           = "ami-0c55b159cbfafe1f0" # Replace with your region's AMI
  instance_type = "t3.micro"

  key_name = "my-ssh-key"

  tags = {
    Environment = "dev"
    Project     = "my-app"
  }

  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-abc12345"

  user_data = file("startup-script.sh")
}

In this example:

  • You’re creating 1 EC2 instance.
  • Assigning it a name, AMI, instance type, and security group.
  • Adding tags for identification and cost tracking.
  • Running a script at startup using “user_data”.

Module Source:

This module is publicly maintained and available on GitHub:

terraform-aws-ec2-instance

Using the EC2 Terraform module not only speeds up your infrastructure deployments but also brings standardization, maintainability, and ease of updates. It’s ideal for teams working across multiple environments and is highly recommended for beginners and seasoned DevOps engineers alike.

3. S3 Bucket Terraform Module

If you’re working with Terraform and managing infrastructure on AWS, there’s a good chance you’ll need to create and manage S3 buckets. While it’s possible to write all the Terraform code yourself from scratch, it’s much easier and faster to use a pre-built Terraform module, and that’s where the Terraform S3 Bucket Module comes in.

What is an S3 Bucket?

In AWS, an S3 bucket is a storage location where you store your files, similar to a cloud-based folder. You can use S3 for backups, hosting websites, storing logs, application data, and much more.

What is the Terraform S3 Bucket Module?

The Terraform S3 Bucket Module is a reusable, community-maintained package of Terraform code that helps you quickly and consistently create and manage S3 buckets with best practices built in.

Instead of writing everything from scratch, you can simply call this Terraform module in your code, configure a few inputs, and you’re good to go.

Why Use the Module?

Here are a few reasons why DevOps engineers and cloud architects like this Terraform module:

Saves Time and Reduces Errors

You don’t need to manually define policies, bucket versioning, logging, encryption, lifecycle rules, etc. The module abstracts all that complexity.

Production-Ready

The module includes secure defaults and best practices out of the box. It’s trusted by thousands of cloud professionals and is ready for real-world use.

Highly Customizable

You can enable or disable features like:

  • Bucket versioning
  • Server-side encryption (SSE)
  • Access logging
  • Lifecycle policies
  • Public access block

Community-Supported

Maintained by the terraform-aws-modules team on GitHub, it has thousands of stars and is widely used in the Terraform community.

How to Use the Module

Here’s a basic example of how to use the module in your Terraform configuration:

module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "~> 3.0"

  bucket = "my-terraform-blog-bucket"
  acl    = "private"

  versioning = {
    enabled = true
  }

  tags = {
    Environment = "dev"
    Project     = "TerraformBlog"
  }
}

This will create an S3 bucket with:

  • Private access
  • Versioning enabled
  • Some basic tags

All in just a few lines of code

Tips for DevOps professionals

  • Always enable versioning to protect against accidental file deletions.
  • Use SSE (Server-Side Encryption) to encrypt data at rest.
  • Enable logging to track access requests and operations on your buckets.
  • Use lifecycle rules to automatically move older objects to different storage classes or delete them based on age or other criteria
  • Don’t forget to block public access unless explicitly required.

The Terraform AWS S3 Bucket Module simplifies your work, reduces duplication, and helps enforce best practices. Whether you’re building a large-scale production system or just getting started with AWS and Terraform, this module is an excellent addition to your infrastructure toolkit.

4. AWS EKS Terraform Module

Setting up Kubernetes on AWS might sound like a complicated task. And it used to be, until Amazon EKS (Elastic Kubernetes Service) and the Terraform AWS EKS module came along. This Terraform module makes deploying a secure, production-ready Kubernetes cluster on AWS as easy as writing a few lines of Terraform code.

What is Amazon EKS?

EKS (Elastic Kubernetes Service) is AWS’s managed Kubernetes service. It handles the control plane (master nodes) for you, things like API servers, etcd, etc. So you only need to worry about the worker nodes (where your applications run).
Think of EKS as AWS saying: “You bring your app, we’ll handle the brain of the Kubernetes cluster.”

What is the Terraform EKS Module?

The Terraform AWS EKS module is a community-maintained module that simplifies the process of spinning up a full-fledged EKS cluster. Created by the terraform-aws-modules team, it follows best practices and saves you hundreds of lines of code and configuration.

Rather than writing everything from scratch, you just call the Terraform module, give it a few inputs like cluster name, node group details, and IAM roles, and it does all the heavy lifting for you.

Why DevOps Engineers Like This Module

Production-Ready in Minutes

Creating an EKS cluster manually could take hours (or days). With this module, it can be done in 10–15 minutes, with best practices built in.

Highly Customizable

  • Specify worker node types (EC2 or Fargate)
  • Define IAM roles and service accounts
  • Use managed node groups or self-managed
  • Enable logging, network policies, and Kubernetes version control

Secure by Default

  • The Terraform module configures proper IAM permissions
  • Private cluster support
  • Security group and VPC integration
  • Kubernetes RBAC mappings

Extensively Used and Tested

It’s used by thousands of DevOps professionals and cloud teams across the world. Bugs are quickly fixed, and new features are added regularly.

Here’s a basic Terraform configuration using the EKS module:

module "eks" {
  source          = "terraform-aws-modules/eks/aws"
  cluster_name    = "my-awesome-cluster"
  cluster_version = "1.29"
  subnet_ids      = module.vpc.private_subnets
  vpc_id          = module.vpc.vpc_id

  eks_managed_node_groups = {
    default = {
      desired_capacity = 2
      max_capacity     = 3
      min_capacity     = 1

      instance_types = ["t3.medium"]
    }
  }

  tags = {
    Environment = "dev"
    Project     = "Terraform-EKS"
  }
}

Just by defining this module, Terraform will:

  • Set up an EKS cluster
  • Create IAM roles
  • Configure networking
  • Deploy worker nodes
  • Handle all security policies

The EKS Terraform module also makes it easier to:

  • Enable OIDC provider for IAM roles for service accounts (IRSA)
  • Set up Kubernetes audit logs
  • Configure private clusters (no public access)
  • Integrate with Fargate for serverless Kubernetes
  • AWS Load Balancer Controller
  • Karpenter for auto-scaling
  • CoreDNS, Metrics Server, ALB Ingress, and more
  • Tools like ArgoCD, Prometheus, Grafana, etc.

Managing Kubernetes clusters manually can be complex, especially in production. But with the Terraform AWS EKS Module, you’re getting a trusted, battle-tested tool that simplifies everything from deployment to security.

Whether you’re running microservices, backend APIs, or ML workloads, this Terraform module can help you spin up and manage a highly available, scalable, and secure Kubernetes cluster on AWS with ease.

5. AWS RDS Terraform module

If your application needs a reliable and scalable database, chances are you’ll want to use Amazon RDS (Relational Database Service). But setting up an RDS instance manually can be complex, especially when you’re dealing with production environments. That’s where the Terraform RDS Module saves the day.

What is Amazon RDS?

Amazon RDS is a fully managed database service by AWS. It supports popular engines like:

  • MySQL
  • PostgreSQL
  • MariaDB
  • SQL Server
  • Oracle
  • Amazon Aurora

RDS takes care of backups, patching, updates, and even scaling, so you can focus on building your app, not managing infrastructure.

What is the Terraform RDS Module?

The Terraform RDS Module is a reusable set of Terraform configurations created by the terraform-aws-modules community. Instead of writing dozens or even hundreds of lines of Terraform code to configure an RDS instance, you can use this Terraform module to quickly launch a secure and production-ready database.

It includes support for:

  • DB instance creation
  • Security groups
  • Subnet groups
  • Backup configurations
  • Multi-AZ deployments
  • Monitoring and maintenance windows

And it’s all wrapped in a few lines of code.

Here’s why DevOps engineers and cloud architects like using this Terraform module:

Time Saver

You don’t need to manually define subnet groups, security rules, storage settings, or monitoring; you just give it a few values and let the Terraform module handle the rest.

Highly Configurable

You can customize:

  • Engine type (MySQL, PostgreSQL, etc.)
  • Instance class (like db.t3.medium)
  • Multi-AZ support for high availability
  • Storage size, encryption, and performance settings
  • Backup windows and retention

Built-in Best Practices

The Terraform module applies secure defaults and best practices, like enabling storage encryption, setting backup retention, and preventing public access.

Production-Ready

Used by thousands of companies, this module has been tested in real-world environments and constantly updated by the community.

Here’s a basic example of how to use the RDS Terraform module in your Terraform code:

module "db" {
  source  = "terraform-aws-modules/rds/aws"
  version = "~> 6.0"

  identifier = "my-app-db"
  engine     = "mysql"
  engine_version = "8.0"
  instance_class = "db.t3.medium"
  allocated_storage = 20

  name     = "mydatabase"
  username = "admin"
  password = "supersecurepassword"
  port     = 3306

  vpc_security_group_ids = [aws_security_group.db_sg.id]
  subnet_ids             = module.vpc.database_subnets

  publicly_accessible = false
  multi_az            = true
  storage_encrypted   = true
  backup_retention_period = 7

  tags = {
    Environment = "production"
    Project     = "terraform-rds"
  }
}

With this simple configuration:

  • A MySQL RDS instance will be launched.
  • It will run in high availability mode (Multi-AZ).
  • It will be encrypted, private, and have 7 days of backups.

Security & Best Practices

The RDS module lets you easily apply strong security controls:

  • Disable public access (by default)
  • Enable encryption at rest
  • Use secure password inputs
  • Attach IAM roles (if needed)
  • Enable enhanced monitoring for better visibility
  • Enable performance insights
  • Add read replicas
  • Use Aurora clusters
  • Configure automatic failover
  • Define maintenance windows to avoid surprises

Managing databases the manual way is slow, error-prone, and hard to scale. The Terraform AWS RDS Module gives you a clean, repeatable, and safe way to provision your databases, whether you’re running a small dev environment or a mission-critical production system.

6. IAM Terraform Module

When working with AWS, IAM (Identity and Access Management) is one of the most critical components. It helps you securely control access to AWS services and resources.

But let’s be honest, writing IAM policies and roles in Terraform can be messy, complex, and error-prone.

That’s where the Terraform IAM Module comes init saves time, reduces complexity, and follows AWS best practices. Let’s explore it step by step in a way that’s easy to understand.

What is IAM in AWS?

IAM (Identity and Access Management) in AWS is a service that helps you securely manage access to AWS services and resources. It lets you control who can access your AWS resources and what actions they can perform, like reading, writing, or deleting data, on those resources.

  • Users: Human users who log in to AWS.
  • Groups: Collections of users.
  • Roles: Temporary access permissions for apps or services.
  • Policies: Documents (written in JSON) that define permissions.

What is the Terraform IAM Module?

The Terraform AWS IAM module is a reusable, open-source component developed by the Terraform AWS Modules community.

It provides a ready-made framework to create:

  • IAM users
  • IAM groups
  • IAM roles (for EC2, Lambda, EKS, etc.)
  • IAM policies (inline and managed)
  • Role trust relationships
  • IAM instance profiles

Instead of manually writing dozens (or hundreds) of lines of IAM code, you can use this Terraform module to handle everything cleanly and efficiently.

Why Use the Terraform IAM Module?

Saves Time and Avoids Repetition: You don’t have to define roles, policies, or trust relationships from scratch. The module does the heavy lifting.

Security Best Practices: The module encourages secure configurations (e.g., least privilege, proper trust policies).

Customizable and Flexible: You can provide your policies or use AWS-managed ones. It supports custom trust policies, path structures, tags, and even multi-account scenarios.

Clean and Readable: Your Terraform code becomes much cleaner and easier to manage.

Creating an IAM Role for EC2

module "iam_ec2_s3" {
  source = "terraform-aws-modules/iam/aws/modules/iam-role"

  name = "ec2-s3-role"
  assume_role_policy = data.aws_iam_policy_document.ec2_assume_role.json

  policy_arns = [
    "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
  ]

  tags = {
    Environment = "dev"
    Project     = "IAM-Module"
  }
}

data "aws_iam_policy_document" "ec2_assume_role" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

This small code snippet will:

  • Create a role named ec2-s3-role
  • Allow EC2 to assume the role
  • Attach the AWS-managed S3 read-only policy
  • Tag the role for identification

Create a Custom IAM Policy

module "custom_policy" {
  source  = "terraform-aws-modules/iam/aws//modules/iam-policy"
  name    = "custom-ec2-policy"
  path    = "/"
  policy  = data.aws_iam_policy_document.custom.json
}

data "aws_iam_policy_document" "custom" {
  statement {
    actions   = ["ec2:Describe*"]
    resources = ["*"]
  }
}

This creates a custom policy that allows only EC2 read-only access.

The IAM module also supports:

  • Cross-account trust for federated access
  • IAM instance profiles for EC2
  • Tags for cost allocation and organization
  • Path-based role organization
  • Group and user management

Best Practices When Using the IAM Module

  • Use the least privilege principle: Grant only the permissions necessary.
  • Use tags to organize and track your IAM resources.
  • Avoid attaching policies directly to users; use groups or roles.
  • Always review the trust policies for roles to avoid privilege escalation.

The Terraform AWS IAM Module is one of the most powerful and widely used modules in the Terraform ecosystem. It helps you build secure, scalable, and manageable IAM structures without writing hundreds of lines of JSON or HCL.

Whether you’re setting up a simple role for EC2 or a complex federated role for cross-account access, this module will save you hours of effort and keep your infrastructure secure and clean.

7. CloudFront with S3 Terraform Module

If you’re hosting a static website, serving assets (like images, CSS, or JS files), or delivering content to users around the world, you’ll want speed, security, and reliability. That’s exactly what the combo of Amazon CloudFront and S3 gives you. Terraform makes deploying this setup super easy with the CloudFront with S3 module.

What Is Amazon CloudFront?

  • CloudFront is AWS’s Content Delivery Network (CDN). It helps you:
  • Deliver your content fast by caching it in edge locations worldwide
  • Reduce load on your servers (especially S3)
  • Improve availability and reliability
  • Add SSL encryption and custom domains

Think of CloudFront as a “global delivery boy” that brings your files closer to your users, no matter where they are.

What Is S3?

Amazon S3 (Simple Storage Service) is an object storage service. You can use it to store:

  • Static websites
  • Images, videos, PDFs
  • Application assets
  • Backups and data exports

When paired with CloudFront, S3 becomes a powerful and scalable content backend.

What Is the Terraform CloudFront with S3 Module?

The Terraform AWS CloudFront with S3 module is a ready-to-use component that helps you set up:

  • An S3 bucket
  • A CloudFront distribution
  • Proper IAM policies
  • Secure access between CloudFront and S3

Instead of manually setting up a CloudFront distribution and configuring dozens of settings, this module does it for you, following AWS best practices.

Why Use This Module?

Saves Time

You can set up a secure, production-ready content delivery solution in minutes.

Security by Default

The module sets up Origin Access Control (OAC) or Origin Access Identity (OAI) so that your S3 bucket can only be accessed through CloudFront, preventing unauthorized access.

Highly Customizable

You can:

  • Enable or disable SSL
  • Add custom domain names (with ACM certificates)
  • Set default root object (like index.html)
  • Add custom error responses
  • Configure cache behaviors

Battle-Tested

This module is maintained by the terraform-aws-modules community, with thousands of users and GitHub stars.

Host a Static Website with CloudFront and S3

module "cloudfront_s3" {
  source = "terraform-aws-modules/cloudfront/aws"

  aliases = ["www.example.com"]

  default_root_object = "index.html"

  viewer_certificate = {
    acm_certificate_arn            = "arn:aws:acm:us-east-1:123456789012:certificate/abcde-1234"
    ssl_support_method             = "sni-only"
    minimum_protocol_version       = "TLSv1.2_2021"
  }

  origin = {
    domain_name = module.s3_bucket.bucket_regional_domain_name
    origin_id   = "s3-origin"

    s3_origin_config = {
      origin_access_identity = module.s3_bucket.cloudfront_origin_access_identity_path
    }
  }

  enabled = true
}

This code will creates:

  • Create a CloudFront distribution pointing to your S3 bucket
  • Use a custom domain (www.example.com)
  • Enable HTTPS using your ACM certificate
  • Secure the S3 bucket using CloudFront’s origin access identity

Security Features

S3 Bucket Restriction: Your bucket can’t be accessed directly; only CloudFront can serve files.

HTTPS/SSL: You can add custom certificates using ACM to serve content over HTTPS.

Geo Restrictions: Block or allow content in specific countries.

WAF Integration: Protect your distribution using AWS Web Application Firewall.

Advanced Features

You can:

  • Add multiple origins (e.g., serve videos from S3 and APIs from an EC2 instance)
  • Customize caching policies (e.g., cache HTML for 5 minutes, images for 1 day)
  • Set up redirects and error pages (e.g., 404.html)
  • Enable logging and metrics to CloudWatch

Use Cases

  • Hosting a static website with global reach
  • Serving static assets for a React/Angular app
  • CDN for media content like images and videos
  • Frontend for serverless applications
  • Delivering documentation or downloadable resources

The Terraform CloudFront with S3 module is the best method if you want to deliver static content securely, quickly, and reliably. It automates a traditionally tedious process and gives you a production-ready CDN setup in minutes with security and performance baked in.

Whether you’re a DevOps engineer, cloud architect, or developer building websites or applications, this module will save you hours and help you scale like a pro.

8. AWS Security Group Terraform Module

When deploying anything on AWS, whether it’s an EC2 instance, a database, or a Kubernetes cluster, security is key. And that’s where Security Groups come in.

But writing and managing AWS Security Groups manually with Terraform can quickly get confusing, especially when your infrastructure grows.

The Terraform AWS Security Group Module simplifies this entire process. It makes your security configuration cleaner, reusable, and much easier to manage.

What Is a Security Group?

A Security Group in AWS acts like a virtual firewall that controls inbound and outbound traffic to AWS resources (like EC2 instances, RDS databases, EKS worker nodes, etc.).

Think of it like:

A list of rules that decide who’s allowed to knock on the door of your cloud server, and who’s not. For example:

  • Allow SSH (port 22) from your office IP
  • Allow HTTP (port 80) from anywhere
  • Block all other traffic by default

What Is the Terraform Security Group Module?

The Terraform AWS Security Group Module is a reusable, open-source module provided by the terraform-aws-modules team. It helps you create and manage Security Groups easily, using simple and readable Terraform code.

Rather than manually writing complex security group rules, this module lets you define your needs in a high-level, structured way, and it takes care of the low-level details.

Example

module "web_sg" {
  source  = "terraform-aws-modules/security-group/aws"
  name    = "web-server-sg"
  vpc_id  = "vpc-12345678"
  description = "Security group for web servers"

  ingress_rules = ["ssh-tcp", "http-80-tcp"]
  ingress_cidr_blocks = ["203.0.113.0/32", "0.0.0.0/0"]

  egress_rules = ["all-all"]
}

This small block of code:

  • Creates a security group named web-server-sg
  • Allows SSH from 203.0.113.0/32
  • Allows HTTP from anywhere
  • Allows all outbound traffic (which is the AWS default)

Self-Referencing Security Group

Sometimes, you want EC2 instances to talk to each other, like app servers connecting on port 8080. Here’s how you can do it:

module "app_sg" {
  source = "terraform-aws-modules/security-group/aws"
  name   = "app-cluster"
  vpc_id = "vpc-xxxxxx"

  ingress_with_self = [
    {
      from_port   = 8080
      to_port     = 8080
      protocol    = "tcp"
      description = "App cluster communication"
    }
  ]
}

This Terraform code allows inbound TCP traffic on port 8080 from other instances in the same security group.

This module supports:

  • Multiple CIDR blocks or security group sources
  • Custom rule definitions (ingress_with_cidr_blocks, egress_with_source_security_group_id)
  • Named ports (https-443-tcp, mysql-tcp)
  • IPv6 support
  • Logging with flow logs (via separate setup)
  • Tagging for tracking

Best Practices

  • Always use descriptive tags and names for your security groups
  • Follow the least privilege principle: only open ports you need
  • Use different SGs for different services (e.g., web, DB, internal apps)
  • Keep ingress and egress rules as minimal as possible
  • Always peer review changes to security rules before applying

The Terraform AWS Security Group Module is a game-changer for cloud engineers who want to manage security in a consistent, scalable, and safe way.

It hides the complexity of AWS security rules and gives you a clean, organized way to define access controls, while following AWS best practices.

Whether you’re deploying a simple web server or a complex microservices architecture, this module will make your life easier and your infrastructure more secure.

Please read our most valueable blog article where you can find that how you can Optimize your AWS Cost.

9. Route 53 DNS Terraform Module

Managing DNS records in AWS manually can get confusing, especially when you have a lot of services running. That’s why AWS Route 53 and Terraform work great together, and using the Terraform Route 53 module makes DNS management simple, scalable, and error-free.

What is Route 53?

Amazon Route 53 is AWS’s scalable and highly available Domain Name System (DNS) web service. It’s used to:

  • Register domain names (like example.com)
  • Route users to AWS services like EC2, S3, or Load Balancers
  • Manage DNS records like A, CNAME, MX, TXT, etc.
  • Think of Route 53 as the “phone book of the internet”; it maps human-readable names (like www.myapp.com) to machine IP addresses (like 192.0.2.1).

What is the Terraform Route 53 Module?

The Terraform AWS Route 53 module simplifies the process of managing Route 53 hosted zones and DNS records using Infrastructure as Code (IaC). It’s part of the terraform-aws-modules collection and helps you:

  • Create and manage public or private hosted zones
  • Add DNS records (A, AAAA, CNAME, TXT, etc.)
  • Manage record sets programmatically
  • Reduce the chances of manual errors

Instead of clicking around in the AWS Console, you define everything in code, and Terraform takes care of applying the changes safely.

Why Use This Module?

Automation: No more manual record creation or worrying about typos. Changes are automated and repeatable.

Speed: Quickly spin up entire DNS zones with all necessary records in seconds.

Version Control: All DNS changes are stored in Git or another VCS, so you can track what changed, when, and by whom.

Error Reduction: Because it’s code, it reduces human error and ensures DNS consistency across environments (dev, staging, prod).

Real-World Use Case

Imagine you launched a web application and want users to access it via app.example.com. You’d need to:

  • Create a Route 53 hosted zone for example.com
  • Add a record for app.example.com pointing to an IP or load balancer

With this module, you can do it like this:

module "dns_zone" {
  source  = "terraform-aws-modules/route53/aws//modules/zone"
  name    = "example.com"
  comment = "Hosted zone for example.com"
}

module "dns_record" {
  source = "terraform-aws-modules/route53/aws//modules/records"

  zone_id = module.dns_zone.zone_id
  records = [
    {
      name = "app"
      type = "A"
      ttl  = 300
      records = ["192.0.2.1"]
    }
  ]
}

This will create:

  • A hosted zone for example.com
  • An A record (app.example.com) that points to the IP 192.0.2.1

No need to touch the AWS console.

Useful Features of the Module

  • Supports multiple record types (A, AAAA, CNAME, MX, TXT, etc.)
  • Supports weighted and failover routing
  • Can create alias records for services like S3 or CloudFront
  • Easily integrates with VPCs for private hosted zones
  • Works well in multi-region/multi-environment setups

Alias Record for Load Balancer

If you’re using an AWS Application Load Balancer and want to point your domain to it:

module "alb_dns_record" {
  source = "terraform-aws-modules/route53/aws/modules/records"

  zone_id = module.dns_zone.zone_id
  records = [
    {
      name = "app"
      type = "A"
      alias = {
        name                   = "dualstack.my-alb-1234567890.us-west-2.elb.amazonaws.com"
        zone_id                = "Z35SXDOTRQ7X7K"
        evaluate_target_health = true
      }
    }
  ]
}

The Terraform Route 53 DNS Module is a must-have tool for anyone managing DNS infrastructure in AWS. It brings consistency, automation, and safety to what is otherwise a tedious and error-prone manual task.

Whether you’re hosting websites, APIs, or internal services, this module helps you:

  • Automate domain setups
  • Simplify record management
  • Reduce DNS misconfiguration risks

10. Null and Local Terraform Module

When working with Terraform, we usually think about creating actual cloud infrastructure like EC2 instances, S3 buckets, VPCs, etc. But sometimes, we need something more flexible, like running scripts, generating files, or working with data that doesn’t directly involve cloud providers.

That’s where Terraform’s null and local modules come in handy. They are special modules that help in logic handling, automation, and data processing, without provisioning any real infrastructure.

What is the Null Provider Module?

The null provider in Terraform is a way to create resources that don’t represent real infrastructure. Instead, it lets you:

  • Run local scripts or shell commands
  • Execute tasks during the apply phase
  • Act as a placeholder for testing or prototyping

Use Case Example: Running a Script After Provisioning

Let’s say you want to run a shell script on your machine after Terraform creates your infrastructure.

resource "null_resource" "run_script" {
  provisioner "local-exec" {
    command = "bash ./post_deploy.sh"
  }

  triggers = {
    always_run = "${timestamp()}"
  }
}
  • It will create a null resource; null_resource is nothing but a dummy resource.
  • local-exec is a provisioner that runs a shell command locally.
  • triggers ensure the resource runs every time (because of the timestamp).

This is perfect for:

  • Running Ansible playbooks
  • Notifying external systems (like sending a Slack message)
  • Running custom cleanup tasks

What is the Local Module?

The local module (using the locals {} block) allows you to define and reuse expressions or values within your Terraform configuration. It’s like setting variables, but for computed or constant values that only exist during the run of the Terraform code.

It will be used for:

  • Simplify long or repeated expressions
  • Improve code readability
  • Help with calculated logic

Example: Reusing Values

locals {
  environment = "production"
  name_prefix = "${local.environment}-web-app"
  region      = "us-east-1"
}

Now you can use these local values in your resources:

resource "aws_instance" "example" {
  ami           = "ami-0abcdef1234567890"
  instance_type = "t2.micro"
  tags = {
    Name = local.name_prefix
  }
}

This way, if you ever want to change “production” to “staging”, you only update it once in the locals {} block.

Combining Null and Local for Custom Logic

You can even combine null and local modules to add advanced logic or behavior into your Terraform workflows.

Example: Notify When the Environment is Production

locals {
  is_production = var.environment == "production"
}

resource "null_resource" "notify" {
  count = local.is_production ? 1 : 0

  provisioner "local-exec" {
    command = "echo 'Production deployment started!'"
  }
}

If the environment is set to production, it will print a message. Otherwise, it won’t run.

Terraform null and local modules may not create real infrastructure, but they’re essential for building smart, maintainable infrastructure as code.

  • Use null_resource for local commands, external triggers, and post-deploy scripts.
  • Use locals {} to simplify and reuse logic in a clean and readable way.

Together, they help you:

  • Add flexibility to your code
  • Reduce repetition
  • Automate tasks outside the cloud

Conclusion

Using a Terraform module is one of the smartest ways to streamline infrastructure management and enforce best practices in any DevOps environment. The 10 modules we’ve explored, ranging from EC2 and VPC setup to IAM, S3, and monitoring, are essential building blocks for automating and scaling cloud infrastructure efficiently.

Whether you’re just getting started with Terraform or managing complex multi-cloud deployments, these reusable modules will save time, reduce errors, and help you stay consistent across environments. By incorporating them into your workflows, you’re not just writing code; you’re building a more stable, maintainable, and secure infrastructure.

Leave a Comment