Skip to content
LATEST

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

Upgradix
Upgradix Code. Learn. Ship.

Variables, Locals, Outputs & Multi-Environment Layouts

To build clean, reusable, and safe infrastructure, you need four core building blocks: typed variables, local expressions, sensitive outputs, and separate environment folders. In this guide, we will break down each one in plain English and refactor a real Node.js and ASP.NET Core setup step by step.

Variables, Locals, Outputs & Multi-Environment Layouts

When you first start writing Terraform (HCL), it is easy to hardcode everything in one file. You write the port number directly, type the server name by hand, and copy-paste the same file when you need a new environment. That works for a weekend demo, but in real-world software teams, hardcoded infrastructure quickly turns into a maintenance nightmare.

To build clean, reusable, and safe infrastructure, you need four core building blocks: typed variables, local expressions, sensitive outputs, and separate environment folders. In this guide, we will break down each one in plain English and refactor a real Node.js and ASP.NET Core setup step by step.

What you will learn
  • How to replace hardcoded values with strongly typed variable blocks and strict validation rules.
  • How to use locals to compute clean names, tags, and shared expressions without repeating yourself.
  • How to expose application endpoints using output blocks and hide secrets using sensitive = true.
  • How to structure separate environment folders (env/dev, env/onprem, env/cloud) for complete blast-radius isolation.
  • Hands-On Lab: Refactor a Node.js and ASP.NET Core Terraform configuration to accept app_env, http_port, and replica_count.

1. Typed Variables, Locals, and Outputs Explained

Think of a Terraform configuration like a function in C# or JavaScript. Variables are the input parameters you pass into the function. Locals are the internal helper variables you calculate inside the function. Outputs are the return values the function hands back when it finishes running.

HCL Block Role When to Use It Example
variable External Input Values that change per environment (ports, replica counts, region). var.http_port
locals Internal Calculation Combining strings, building standard resource names, or merging common tags. local.name_prefix
output Return Value Printing service URLs, IP addresses, or passing values to CI/CD pipelines. terraform output

Why Type Constraints and Validation Matter

If you leave a variable untyped, someone could accidentally pass "three" instead of 3 for a replica count, or pass port 99999 which does not exist. Adding type and validation blocks catches these mistakes immediately during terraform plan—before Terraform ever tries to touch your servers or cloud account.

Important: Always mark passwords, connection strings, and API tokens with sensitive = true in both your variable and output blocks. This stops Terraform from printing secrets in plain text inside your terminal or CI/CD logs.

2. Multi-Environment Folder Layout (env/dev, env/onprem, env/cloud)

A common mistake is putting all environments into a single folder and relying on Terraform Workspaces. While workspaces work for small experiments, production teams prefer separate environment folders. Each folder has its own state file, its own variable values, and zero risk of a dev change accidentally wiping out production.

Recommended Multi-Environment Directory Structure

infra/
├── modules/
│   └── app-stack/               # Shared Node.js + ASP.NET Core module
│       ├── main.tf
│       ├── variables.tf         # Typed inputs + validation rules
│       ├── locals.tf            # Naming conventions & shared tags
│       └── outputs.tf           # Endpoints & sensitive outputs
└── env/
    ├── dev/                     # Local / Dev environment
    │   ├── main.tf
    │   └── terraform.tfvars
    ├── onprem/                  # On-Premises data center
    │   ├── main.tf
    │   └── terraform.tfvars
    └── cloud/                   # AWS / Azure Production Cloud
        ├── main.tf
        └── terraform.tfvars

3. How Data Flows Across Environments

When you run terraform apply inside env/dev, env/onprem, or env/cloud, Terraform reads that folder's terraform.tfvars file, validates the inputs against variables.tf, builds standardized names in locals.tf, provisions your Node.js and ASP.NET Core services, and exposes the final URLs through outputs.tf.

Terraform Multi-Environment Data Flow

env/dev replicas=1, :3000 env/onprem replicas=2, :8080 env/cloud replicas=4, :80 variables.tf Typed Inputs & Validation Rules locals.tf Names & Tags main.tf Node.js UI & ASP.NET Core API outputs.tf App URLs & Sensitive Keys

Each environment folder passes its own values into the shared module. Variables are validated first, transformed by locals, applied to the Node.js and ASP.NET Core services, and finally exposed as outputs.

4. Hands-On Lab: Refactoring Node.js & ASP.NET Core Infrastructure

Let's refactor a hardcoded Node.js frontend and ASP.NET Core Web API setup into a clean, reusable module. We will accept app_env, http_port, and replica_count, enforce strict validation rules, and expose the endpoints via terraform output.

Step 1: Define Typed Variables & Validation Rules

Create modules/app-stack/variables.tf. Notice how we restrict app_env to only allowed values, ensure http_port is a valid network port, and cap replica_count so nobody accidentally spins up 500 servers.

modules/app-stack/variables.tf

variable "app_env" {
  description = "Target deployment environment (dev, onprem, or cloud)."
  type        = string

  validation {
    condition     = contains(["dev", "onprem", "cloud"], var.app_env)
    error_message = "app_env must be one of: dev, onprem, or cloud."
  }
}

variable "http_port" {
  description = "External HTTP port for the Node.js and ASP.NET Core gateway."
  type        = number
  default     = 8080

  validation {
    condition     = var.http_port >= 80 && var.http_port <= 65535
    error_message = "http_port must be a valid port between 80 and 65535."
  }
}

variable "replica_count" {
  description = "Number of container replicas to run for each service."
  type        = number
  default     = 1

  validation {
    condition     = var.replica_count >= 1 && var.replica_count <= 10
    error_message = "replica_count must be between 1 and 10."
  }
}

variable "db_connection_string" {
  description = "Database connection string for the ASP.NET Core API."
  type        = string
  sensitive   = true
}

Step 2: Centralize Naming and Tags with Locals

Create modules/app-stack/locals.tf. Instead of repeating "upgradix-${var.app_env}-..." ten times across your files, calculate it once here.

modules/app-stack/locals.tf

locals {
  project_name = "upgradix"
  name_prefix  = "${local.project_name}-${var.app_env}"

  # Calculate the ASP.NET Core internal API port relative to the main HTTP port
  dotnet_api_port = var.http_port + 1

  common_tags = {
    Project     = local.project_name
    Environment = var.app_env
    ManagedBy   = "Terraform"
  }
}

Step 3: Provision Node.js & ASP.NET Core Services

Create modules/app-stack/main.tf. Here we use the Docker provider so you can run this exact lab locally or on-prem, while keeping the structure identical to cloud container services like AWS ECS.

modules/app-stack/main.tf

resource "docker_container" "nodejs_web" {
  count = var.replica_count
  name  = "${local.name_prefix}-nodejs-${count.index + 1}"
  image = "node:20-alpine"

  env = [
    "NODE_ENV=${var.app_env}",
    "API_BASE_URL=http://${local.name_prefix}-dotnet-1:${local.dotnet_api_port}"
  ]

  ports {
    internal = 3000
    external = var.http_port + count.index
  }
}

resource "docker_container" "dotnet_api" {
  count = var.replica_count
  name  = "${local.name_prefix}-dotnet-${count.index + 1}"
  image = "mcr.microsoft.com/dotnet/aspnet:8.0"

  env = [
    "ASPNETCORE_ENVIRONMENT=${title(var.app_env)}",
    "ConnectionStrings__DefaultConnection=${var.db_connection_string}"
  ]

  ports {
    internal = 8080
    external = local.dotnet_api_port + count.index
  }
}

Step 4: Expose Endpoints & Protect Sensitive Outputs

Create modules/app-stack/outputs.tf. This prints the clickable URLs for your Node.js and ASP.NET Core services while masking the database connection string.

modules/app-stack/outputs.tf

output "nodejs_endpoints" {
  description = "Accessible HTTP endpoints for the Node.js frontend replicas."
  value       = [for idx in range(var.replica_count) : "http://localhost:${var.http_port + idx}"]
}

output "dotnet_api_endpoints" {
  description = "Accessible HTTP endpoints for the ASP.NET Core Web API replicas."
  value       = [for idx in range(var.replica_count) : "http://localhost:${local.dotnet_api_port + idx}/swagger"]
}

output "api_connection_string" {
  description = "Masked database connection string for verification."
  value       = var.db_connection_string
  sensitive   = true
}

Step 5: Wire Up an Environment Folder (env/dev)

Now inside env/dev/main.tf and env/dev/terraform.tfvars, we call the shared module with dev-specific settings.

env/dev/main.tf

module "app_stack" {
  source               = "../../modules/app-stack"
  app_env              = var.app_env
  http_port            = var.http_port
  replica_count        = var.replica_count
  db_connection_string = var.db_connection_string
}

output "nodejs_urls" {
  value = module.app_stack.nodejs_endpoints
}

output "dotnet_api_urls" {
  value = module.app_stack.dotnet_api_endpoints
}

env/dev/terraform.tfvars

app_env       = "dev"
http_port     = 3000
replica_count = 2

Running the Lab & Expected Output

$ cd infra/env/dev
$ terraform init
$ terraform apply -var="db_connection_string=Server=db;User=sa;Pass=Secret123!" -auto-approve

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

Outputs:

dotnet_api_urls = [
  "http://localhost:3001/swagger",
  "http://localhost:3002/swagger",
]
nodejs_urls = [
  "http://localhost:3000",
  "http://localhost:3001",
]

5. Step-by-Step Execution Breakdown

Here is what happens under the hood when you execute terraform apply in this layout:

Step 1: Terraform loads env/dev/terraform.tfvars and any -var CLI flags.
Step 2: Before creating any resources, Terraform checks every validation block in variables.tf. If replica_count = 50, it stops immediately with your custom error message.
Step 3: Terraform evaluates locals.tf to generate upgradix-dev and compute the internal API port.
Step 4: Terraform loops using count = var.replica_count to spin up the exact number of Node.js and ASP.NET Core containers.
Step 5: Once created, terraform output prints the generated endpoints while hiding any output marked sensitive = true.
Watch out: Never commit secrets (like db_connection_string) inside terraform.tfvars in Git! Even with sensitive = true, the value is still stored in your Terraform state file (terraform.tfstate). Always use encrypted remote state (like AWS S3 with KMS) and pass secrets via environment variables (TF_VAR_db_connection_string) or a secrets manager.

6. Hands-On Practice

Test your understanding by extending the lab configuration above:

Beginner Exercise 1: Trigger a Validation Error

Change app_env = "staging" inside env/dev/terraform.tfvars and run terraform plan.

Hint: Observe how Terraform blocks the deployment before talking to any provider because "staging" is not in the allowed list.

Intermediate Exercise 2: Create the On-Prem Environment

Copy env/dev into env/onprem. Configure it with app_env = "onprem", http_port = 8080, and replica_count = 3.

Expected result: Running terraform output -json should display 3 Node.js endpoints and 3 ASP.NET Core endpoints without affecting your dev environment.

Advanced Exercise 3: Add a Custom Port Conflict Check

Notice in our lab that if replica_count = 2 and http_port = 3000, Node.js uses ports 3000 and 3001, while ASP.NET Core uses 3001 and 3002—causing a port collision on 3001! Refactor locals.tf so the ASP.NET Core port always starts at var.http_port + 100.

Hint: Update dotnet_api_port = var.http_port + 100 in locals.tf and re-run terraform plan.

7. Interview Questions

Hiring managers love asking about Terraform structure and state safety. Here is how to answer like a senior architect:

Q1. What is the difference between a variable and a local in Terraform?

Answer: A variable is an external input whose value can be changed per environment using .tfvars files or CLI flags. A local is an internal, computed expression that cannot be overridden from outside the module. Use locals to avoid repeating complex naming or tagging logic.

Q2. Why do teams use separate folders (env/dev, env/cloud) instead of Terraform Workspaces?

Answer: Separate folders provide stronger isolation. Each environment can have different backend credentials, different Terraform provider versions, and completely separate state files. With workspaces, all environments share the exact same backend configuration and code, which increases the risk of accidentally applying a dev change to production.

Q3. Does setting sensitive = true on an output encrypt it in the Terraform state file?

Answer: No. Setting sensitive = true only masks the value in CLI terminal output and CI/CD logs. The actual value is still stored in plain text inside terraform.tfstate. To protect it at rest, you must use an encrypted remote backend like AWS S3 with SSE-KMS and strict IAM access controls.

Conclusion

Moving away from hardcoded Terraform files is the single biggest step toward production-ready Infrastructure as Code. By combining strongly typed variables, validation rules, reusable locals, and isolated environment folders (env/dev, env/onprem, env/cloud), your Node.js and ASP.NET Core deployments become predictable, safe, and easy for any team member to maintain.

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.