Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 22, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

      July 22, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 22, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Operating Systems»Linux»Modules in Terraform: Creating Reusable Infrastructure Code

    Modules in Terraform: Creating Reusable Infrastructure Code

    July 21, 2025

    Welcome to Terraform Modules, Infra Coders!

    Hey there, Infra coders! So far, you’ve mastered installing Terraform, connecting it to a cloud provider, and understanding the all-important state file. Now, let’s level up with Terraform modules. Think of modules as reusable blueprints—like a recipe you can use to cook the same dish in different kitchens without rewriting the whole thing. Modules make your Terraform code cleaner, reusable, and easier to manage, especially when your projects get bigger or involve a team.

    In this article, we’ll explore what modules are, why they’re awesome, how to create and use them, and some best practices to keep your code tidy. Let’s jump in!

    Understanding Terraform Modules
    Understanding Terraform Modules

    What Are Terraform Modules?

    A Terraform module is a set of Terraform configuration files grouped together to create a specific piece of infrastructure. Instead of writing the same code over and over for, say, an S3 bucket or a virtual machine, you bundle that code into a module. Then, you can reuse it across projects or environments (like dev, staging, or prod) with just a few tweaks.

    For example, imagine you need an S3 bucket with specific settings in multiple projects. Without modules, you’d copy-paste the same code everywhere. With a module, you write the bucket code once, store it in a folder, and call it whenever you need it. It’s like having a LEGO block you can snap into any creation!

    Why Use Modules?

    Modules are a game-changer for several reasons:

    • Reusability: Write once, use everywhere. No more copy-pasting!
    • Consistency: Ensure the same setup (like an S3 bucket or server) is identical across projects.
    • Simplicity: Break complex infrastructure into smaller, manageable pieces.
    • Team Collaboration: Share modules with your team to standardize infrastructure.
    • Less Maintenance: Update a module in one place, and all projects using it get the update.

    How Do Modules Work?

    A module is just a folder with Terraform files (like main.tf, variables.tf, or outputs.tf). You call a module from your main Terraform configuration using a module block. Here’s the basic flow:

    1. Create a Module: Write Terraform code in a folder (e.g., s3-module/) to define a resource like an S3 bucket.
    2. Use the Module: In your main project, reference the module and pass in custom settings (like the bucket name).
    3. Run Terraform: Terraform combines the module’s code with your configuration and creates the resources.

    Let’s walk through creating and using a module to see it in action.

    Step 1: Creating Your First Module

    Let’s create a simple module to set up an AWS S3 bucket with some standard settings. Create a folder structure like this:

    
    my-project/
    ├── main.tf
    └── s3-module/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf
    
    

    Write the Module Code

    In the s3-module/ folder, add these files:

    In s3-module/main.tf:

    
    resource "aws_s3_bucket" "bucket" {
      bucket = var.bucket_name
      tags   = {
        Environment = var.environment
      }
    }
    
    

    In s3-module/variables.tf:

    
    variable "bucket_name" {
      description = "Name of the S3 bucket"
      type        = string
    }
    
    variable "environment" {
      description = "Environment for the bucket (e.g., dev, prod)"
      type        = string
      default     = "dev"
    }
    
    

    In s3-module/outputs.tf:

    
    output "bucket_id" {
      description = "The ID of the created S3 bucket"
      value       = aws_s3_bucket.bucket.id
    }
    
    

    This module creates an S3 bucket with a name and environment tag you specify. The outputs.tf file lets you retrieve the bucket’s ID for use elsewhere.

    Step 2: Using the Module

    Now, let’s use this module in your main project. In my-project/main.tf, add:

    
    provider "aws" {
      region = "us-east-1"
    }
    
    module "my_s3_bucket" {
      source      = "./s3-module"
      bucket_name = "my-unique-bucket-123"
      environment = "prod"
    }
    
    output "bucket_id" {
      value = module.my_s3_bucket.bucket_id
    }
    
    

    Here’s what’s happening:

    • The module block calls the s3-module folder using source = "./s3-module".
    • We pass in values for bucket_name and environment.
    • The output block grabs the bucket ID from the module to display it after creation.

    Step 3: Running the Module

    Navigate to your my-project/ folder in your terminal and run these commands:

    1. Initialize: Downloads the AWS provider and sets up the module:
      terraform init
      
    2. Plan: Checks what Terraform will create:
      terraform plan
      
    3. Apply: Creates the S3 bucket:
      terraform apply
      

      Type yes to confirm, and Terraform will create the bucket using your module. You’ll also see the bucket ID in the output.

    Terraform Modules
    Terraform Modules

    Where to Store Modules

    You can store modules in a few places:

    • Local Path: Like ./s3-module, great for testing or small projects.
    • Git Repository: Host modules on GitHub or GitLab (e.g., source = "git::https://github.com/your-repo/s3-module.git") for team sharing.
    • Terraform Registry: Use public or private modules from registry.terraform.io (e.g., source = "terraform-aws-modules/s3-bucket/aws").

    For example, to use a public module from the Terraform Registry, you could replace your module with:

    
    module "my_s3_bucket" {
      source  = "terraform-aws-modules/s3-bucket/aws"
      version = "4.1.0"
      bucket  = "my-unique-bucket-123"
    }
    
    

    This pulls a community-tested S3 module, saving you time.

    Best Practices for Terraform Modules

    To keep your modules clean and effective, follow these tips:

    • Keep Modules Focused: Each module should do one thing well (e.g., create an S3 bucket, not a bucket plus a database).
    • Use Variables: Make modules flexible with variables for names, regions, or other settings.
    • Document Everything: Add descriptions to variables and outputs to make your module user-friendly.
    • Version Modules: If sharing modules via Git or Terraform Registry, use version tags (like v1.0.0) to track changes.
    • Test Modules: Test your module in a sandbox environment before using it in production.
    • Avoid Hardcoding: Don’t put fixed values (like bucket names) in the module—use variables instead.

    Cleaning Up

    To remove the S3 bucket you created, run:

    terraform destroy
    

    Type yes to confirm, and Terraform will delete the bucket. This keeps your AWS account tidy and cost-free.

    What’s Next?

    Great job, Infra coders! You’ve just built and used your first Terraform module. You’re now ready to make your infrastructure code reusable and organized. In the next article, we’ll dive into variables and outputs to make your Terraform setups even more flexible and powerful. Keep coding, and see you soon!

    The post Modules in Terraform: Creating Reusable Infrastructure Code appeared first on TecAdmin.

    Source: Read More

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleBeyond the Corporate Mold: How 21 TSI Sets the Future of Sports in Motion
    Next Article A Primer on Focus Trapping

    Related Posts

    News & Updates

    A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

    July 22, 2025
    News & Updates

    “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

    July 22, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-31946 – Pixmeo OsiriX MD Local Use After Free Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-4538 – KKFileView Unrestricted File Upload Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    “Every gamer should replace their AirPods with these.” — Prime Day has made these GameBuds cheaper than ever

    News & Updates

    Amazon delays Alexa.com’s launch to “no sooner than July 31” — as OpenAI preps to topple Google Chrome’s dominance in the coming weeks

    News & Updates

    Highlights

    CVE-2025-4059 – Code-projects Prison Management System Stack-Based Buffer Overflow

    April 29, 2025

    CVE ID : CVE-2025-4059

    Published : April 29, 2025, 12:15 p.m. | 3 hours, 48 minutes ago

    Description : A vulnerability classified as critical was found in code-projects Prison Management System 1.0. This vulnerability affects the function addrecord of the component Prison_Mgmt_Sys. The manipulation of the argument filename leads to stack-based buffer overflow. An attack has to be approached locally. The exploit has been disclosed to the public and may be used.

    Severity: 5.3 | MEDIUM

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    CVE-2025-4380 – Adobe Ads Pro Plugin Local File Inclusion Vulnerability

    July 2, 2025

    5 pocket-friendly gadgets I take everywhere (and why they make such a big difference)

    July 1, 2025

    Introduction to Object-Oriented UX

    May 30, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.