Skip to content
LATEST

🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.

Upgradix
Upgradix Code. Learn. Ship.

Reusable Terraform Modules for On-Prem & Cloud Targets

Published · Package compute, networking, and firewall rules into versioned Terraform modules so on-premises servers and cloud instances share consistent baselines.

Reusable Terraform Modules for On-Prem & Cloud Targets

Most real-world companies do not run 100% in the cloud. They run hybrid environments: some workloads stay on local data-center servers for compliance or cost reasons, while others scale out in AWS, Azure, or GCP. When teams write separate, copy-pasted infrastructure scripts for each environment, firewall rules drift, ports get misconfigured, and deployments break.

By packaging compute, networking, and firewall rules into versioned Terraform modules, you enforce one consistent baseline across both on-premises servers and cloud instances.

What you will learn
  • Why copy-pasting Terraform files between on-prem and cloud causes configuration drift.
  • How to design a clean, versioned module contract using variables.tf, main.tf, and outputs.tf.
  • Hands-On Lab: Build a reusable service_runtime module that accepts an app image and port.
  • Invoke the exact same module twice—once for a local/on-prem container host and once for a cloud-simulated target—and verify both endpoints respond.
  • Senior architecture trade-offs: state isolation, provider aliases, and semantic versioning.

1. The Problem Context: Why Hybrid Environments Drift

When an engineering team manages both on-prem servers and cloud instances without reusable modules, infrastructure quickly becomes fragile. One engineer opens port 8080 on a local server manually, while another configures a cloud security group with a different CIDR block.

  • The Scenario: Your team needs to deploy the same microservice to an on-premises container host in the office data center and to a cloud environment for external traffic.
  • The Error/Pain Point: Without a shared module, each environment has its own hand-written Terraform files. A security patch or health-check update applied to the cloud target gets forgotten on-prem, leading to failed audits and broken production rollouts.
Baseline Layer On-Premises Target Cloud Target (AWS / Azure / GCP) Shared Module Contract
Compute Local Docker host / VMware / Bare metal ECS, EKS, EC2, or Container Apps app_image, cpu_limit, memory_mb
Networking Bridge / VLAN / Internal subnet VPC / Private & Public Subnets network_name, internal_port, external_port
Firewall / Security Host firewall / iptables / Local reverse proxy Security Groups / NACLs allowed_cidrs, ingress_protocol

2. Architecture & Workflow Visualized

Instead of writing duplicate resource blocks, you create a single versioned module (service_runtime). Your root configuration calls that module twice with different input variables. Both targets inherit the exact same labeling, networking isolation, restart policies, and port exposure rules.

One Versioned Module Provisioning Both On-Prem & Cloud Targets

Module: service_runtime (v1.0.0) Inputs: app_image · app_port · allowed_cidrs target = "onprem" target = "cloud-sim" On-Premises Container Host Network: onprem-net (isolated) Firewall Baseline: 127.0.0.1:8081 → 80 Cloud-Simulated Target Network: cloud-sim-vpc (isolated) SG Baseline: 0.0.0.0:8082 → 80 http://localhost:8081 · 200 OK http://localhost:8082 · 200 OK

Both environments are created from the exact same Terraform module. Only the input parameters (target name, bind address, and host port) change.

3. Hands-On Lab: Build the Reusable service_runtime Module

In this lab, we will use the Terraform Docker provider so you can run the entire hybrid simulation on your own machine without paying for cloud bills. Make sure you have Docker and Terraform (1.6+) installed.

Project Folder Structure

Create the following directory layout. Keeping modules inside a dedicated modules/ folder makes them easy to extract into a separate Git repository later.

Directory layout

terraform-hybrid-lab/
├── main.tf
├── outputs.tf
└── modules/
    └── service_runtime/
        ├── versions.tf
        ├── variables.tf
        ├── main.tf
        └── outputs.tf

Step 1: Define the Module Provider Requirements

Every reusable module should declare its required provider constraints in versions.tf without hardcoding provider credentials or host URLs. That way, the caller decides which host or cloud account to target.

modules/service_runtime/versions.tf

terraform {
  required_version = ">= 1.6.0"

  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 3.0"
    }
  }
}

Step 2: Define the Module Input Contract

The variables.tf file acts as the API for your module. Notice how we add validation blocks to stop bad port numbers or invalid environment names before Terraform even tries to deploy.

modules/service_runtime/variables.tf

variable "service_name" {
  description = "Unique name for the service instance"
  type        = string
}

variable "target_env" {
  description = "Deployment target baseline (onprem or cloud-sim)"
  type        = string

  validation {
    condition     = contains(["onprem", "cloud-sim"], var.target_env)
    error_message = "target_env must be either 'onprem' or 'cloud-sim'."
  }
}

variable "app_image" {
  description = "Container image to deploy (e.g., nginx:alpine)"
  type        = string
}

variable "internal_port" {
  description = "Port the application listens on inside the container"
  type        = number
  default     = 80
}

variable "external_port" {
  description = "Host port exposed for external traffic"
  type        = number

  validation {
    condition     = var.external_port >= 1024 && var.external_port <= 65535
    error_message = "external_port must be an unprivileged port between 1024 and 65535."
  }
}

variable "bind_ip" {
  description = "Firewall/binding baseline IP (127.0.0.1 for local-only, 0.0.0.0 for public)"
  type        = string
  default     = "127.0.0.1"
}

Step 3: Package Compute, Networking & Firewall Baseline

In modules/service_runtime/main.tf, we bundle three things together: an isolated network, the container image pull, and the running compute container with standardized labels and port-binding rules.

modules/service_runtime/main.tf

# 1. Isolated Network Baseline
resource "docker_network" "service_net" {
  name = "${var.service_name}-${var.target_env}-net"
}

# 2. Pull the Application Image
resource "docker_image" "app" {
  name         = var.app_image
  keep_locally = true
}

# 3. Compute + Firewall/Port Binding Baseline
resource "docker_container" "service" {
  name    = "${var.service_name}-${var.target_env}"
  image   = docker_image.app.image_id
  restart = "unless-stopped"

  # Attach to the isolated network
  networks_advanced {
    name = docker_network.service_net.name
  }

  # Firewall & port exposure baseline
  ports {
    internal = var.internal_port
    external = var.external_port
    ip       = var.bind_ip
  }

  # Consistent governance labels across on-prem and cloud
  labels {
    label = "managed_by"
    value = "terraform"
  }

  labels {
    label = "target_env"
    value = var.target_env
  }
}

Step 4: Expose Module Outputs

Always return the endpoint URL and container ID so the calling configuration (or a CI/CD pipeline) can run automated smoke tests immediately after deployment.

modules/service_runtime/outputs.tf

output "endpoint_url" {
  description = "HTTP endpoint to verify the running service"
  value       = "http://localhost:${var.external_port}"
}

output "container_name" {
  description = "Provisioned container name"
  value       = docker_container.service.name
}

output "network_name" {
  description = "Isolated network created for this target"
  value       = docker_network.service_net.name
}

4. Invoking the Module for On-Prem & Cloud-Simulated Targets

Now move to the root folder (terraform-hybrid-lab/). Here, we invoke service_runtime twice: once for the on-premises target (bound strictly to 127.0.0.1:8081) and once for the cloud-simulated target (exposed on 0.0.0.0:8082).

main.tf (Root Configuration)

terraform {
  required_version = ">= 1.6.0"

  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 3.0"
    }
  }
}

provider "docker" {}

# Invocation 1: Local / On-Premises Container Host
module "onprem_service" {
  source        = "./modules/service_runtime"
  service_name  = "orders-api"
  target_env    = "onprem"
  app_image     = "nginx:alpine"
  internal_port = 80
  external_port = 8081
  bind_ip       = "127.0.0.1" # Restricted local firewall baseline
}

# Invocation 2: Cloud-Simulated Target
module "cloud_sim_service" {
  source        = "./modules/service_runtime"
  service_name  = "orders-api"
  target_env    = "cloud-sim"
  app_image     = "nginx:alpine"
  internal_port = 80
  external_port = 8082
  bind_ip       = "0.0.0.0" # Public cloud ingress baseline
}

outputs.tf (Root Configuration)

output "onprem_endpoint" {
  value = module.onprem_service.endpoint_url
}

output "cloud_sim_endpoint" {
  value = module.cloud_sim_service.endpoint_url
}

5. Step-by-Step Deployment & Verification

Step 1: Initialize Terraform to download the Docker provider and register your local module.
Step 2: Apply the configuration to spin up both isolated networks and containers.
Step 3: Use curl to verify that both the on-prem and cloud-simulated endpoints return HTTP 200 OK.

Run Terraform & verify both endpoints

terraform init
terraform apply -auto-approve

# Verify On-Premises Target (Port 8081)
curl -I http://localhost:8081

# Verify Cloud-Simulated Target (Port 8082)
curl -I http://localhost:8082

Expected output

Apply complete! Resources: 6 added, 0 changed, 0 destroyed.

Outputs:

cloud_sim_endpoint = "http://localhost:8082"
onprem_endpoint = "http://localhost:8081"

HTTP/1.1 200 OK
Server: nginx/1.27.x
...

HTTP/1.1 200 OK
Server: nginx/1.27.x
Cleanup: When you finish testing the lab, run terraform destroy -auto-approve to cleanly remove both containers and networks.

6. Architecture & Real-World Trade-offs

Running a local lab is great for learning, but production hybrid infrastructure requires careful architectural decisions. Here is what matters when you scale this pattern across real data centers and AWS/Azure accounts:

  • Pin Module Versions with Git Tags: Never point production environments at a main branch. Publish your module to a Git repository or private Terraform Registry and reference a specific tag, such as git::https://github.com/your-org/tf-modules.git//service_runtime?ref=v1.2.0. That way, an update for the cloud team never accidentally breaks an on-prem server during an unrelated apply.
  • Isolate State Files per Target: In our lab, both modules shared one terraform.tfstate file for simplicity. In production, separate state files for on-prem and cloud. If an on-prem VPN drops, you still want to be able to run terraform apply on your cloud environment without state locks blocking you.
  • Avoid "Mega-Modules": Do not try to cram every AWS EC2 option and every VMware vSphere option into a single giant module with 50 if/else flags. Keep the module contract small and focused on the shared baseline (compute, network, firewall).
Watch out: Never put provider {} configuration blocks inside a reusable child module. If you hardcode provider settings inside a child module, you cannot pass different provider aliases (like docker.onprem and docker.cloud) from the root configuration.

7. Hands-On Practice

Beginner Exercise 1: Add Memory Limits

Update modules/service_runtime/variables.tf to accept a memory_mb variable (default 128) and wire it into the memory argument of docker_container.service.

Hint: Set memory_mb = 256 for the cloud-simulated target and 128 for on-prem, then run terraform plan.

Intermediate Exercise 2: Inject Environment Variables

Add an env_vars map variable to the module so each target can pass its own configuration (such as APP_ENV=onprem vs APP_ENV=cloud).

Expected result: Running docker inspect orders-api-onprem shows the injected environment variable.

Advanced Exercise 3: Multi-Host Provider Aliases

Configure two aliased Docker providers in your root main.tf and pass them into each module call using the providers = { docker = ... } meta-argument.

Hint: This is the exact pattern used in production to deploy to multiple AWS regions or separate on-prem Docker daemons over SSH.

8. Interview Questions

Q1. Why should child Terraform modules avoid defining provider blocks?

Answer: Child modules should inherit providers from the root module. Defining a provider block inside a child module prevents callers from using for_each, count, or provider aliases to deploy the same module across multiple regions, accounts, or on-prem hosts.

Q2. How do you safely roll out a breaking change to a shared Terraform module used by both on-prem and cloud teams?

Answer: Use semantic versioning (e.g., v2.0.0) via Git tags or a private Terraform Registry. Keep existing environments pinned to v1.x, upgrade a non-production target to v2.0.0 first, verify with terraform plan, and then promote the version bump gradually.

Q3. Should on-premises and cloud environments share a single Terraform state file?

Answer: No. Sharing a single state file increases the blast radius and couples availability—if the on-prem network is unreachable, cloud deployments fail too. Each environment should have its own isolated remote state backend with state locking enabled.

Conclusion

Reusable Terraform modules turn hybrid infrastructure from a maintenance nightmare into a predictable, repeatable system. By packaging compute, networking, and firewall rules behind a clean variable contract, you guarantee that every on-premises server and cloud instance follows the exact same security and operational baseline.

Have a different module structure or hybrid deployment pattern? Share your approach on Upgradix by Shrash Studio to help the community and earn goodies for your contributions.

Official Documentation

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Discussion & Comments

0
Guest mode · Login / Register
Post directly as a guest or log in first.

No comments yet

Start the discussion above — ask a question, share a tip, or reply to a comment.

This article is protected. Printing and saving as PDF are disabled.