Skip to content

Terraform-based Infrastructure Provisioning: Principles, State, and Repository Structure

Interactive Diagram

새 탭 ↗

When building a cloud-based system, managing infrastructure as code isn’t a choice; it’s a prerequisite. This article summarizes the core principles of IaC (Infrastructure as Code) and Terraform’s key concepts/syntax, explains how we built a CommentOps pipeline using a Terraform Automation & Collaboration Tool (TACOS), and covers the actual structure we used to deploy Network/Managed Resources.

Environment separation (dev/stg/prd) is summarized in Separating environments at the end, and this article focuses on how the CommentOps pipeline itself was assembled and operated and on the actual Network/Managed Resource deployment structure.

Core Principles of IaC (Infrastructure as Code)

Section titled “Core Principles of IaC (Infrastructure as Code)”
  • Infrastructure as code: Manage all network configuration as code, track change history through version control, and implement a repeatable deployment process.
  • Idempotency: Running the same code always produces the same result. Existing resource state is checked first and only the necessary changes are applied, preventing accidental duplicate runs.
  • Declarative configuration: Define the desired end state as code and automatically resolve the gap between current and target state. This is the key principle for preventing manual configuration errors.
  • Modularity and reusability: Modularize common infrastructure components and separate per-environment variables to enable reuse.
  • Automation and pipeline integration: Integrate with CI/CD pipelines, extending to automated testing/validation and automated approval workflows.

During implementation, you also need to consider security (sensitive-value management, RBAC), state management (remote state store, state locking), and change management (Plan pre-validation, rollback strategy).

  • Uses a cloud-neutral configuration language, HCL (HashiCorp Configuration Language)
  • Strong state-management features (terraform.tfstate)
  • A rich provider ecosystem: AWS, Azure, GCP, OpenStack, and more
  • A declarative approach to defining infrastructure
  • provider: The infrastructure provider that Terraform will target
  • resource: An actual piece of infrastructure to create (e.g. azurerm_linux_virtual_machine)
  • output: Exposes specific values from a created resource so they can be referenced later from a remote state
  • backend: How Terraform stores its state. With a remote backend, the latest deployed state is stored externally
  • remote state: An approach for managing the .tfstate file remotely, typically backed by object storage
  • module: A unit that groups commonly reused infrastructure code together. You can easily recreate the same resources by simply changing variables.
CommandDescriptionBehaviorNotes
terraform initInitialize the working directoryDownloads plugins, initializes the backend, sets up the working directory--upgrade: upgrades to the latest plugin version that satisfies constraints. --migrate / --reconfigure: for state file changes or reconfiguration
terraform planGenerate an execution planValidation, state comparison, plan generationAlways review the plan summary, e.g. “Plan: 2 to add, 1 to change, 0 to destroy”
terraform applyProvision infrastructure per the execution planCreates resources, updates the state file--auto-approve: proceeds automatically without confirmation
terraform destroyRemove managed infrastructure resourcesDeletes resources, updates the state fileBe careful; losing the link to the state file can cause the managed state to fall out of sync

As Terraform performs its work, it creates a state file (.tfstate) to track the current state of the infrastructure. This can be managed as Local State or Remote State. If you have multiple collaborators, need confidentiality, or need object locking, we recommend managing it with an object-storage-based remote backend (e.g. Azure Storage Blob).

Implementations are composed of four building blocks: resource, data, variable, and output.

resource "azurerm_virtual_network" "vnet" {
name = var.name
location = var.location
address_space = [var.address_space]
resource_group_name = var.resource_group_name
tags = var.common_tags
}
data "azurerm_virtual_network" "vnet_data" {
name = var.aks_vnet_name
resource_group_name = var.resource_group_name
}
variable "name" {
type = string
description = "The name of the AKS cluster"
}
variable "location" {
type = string
description = "The location of the AKS cluster"
}
output "subnet_ids" {
value = values(azurerm_subnet.subnets)[*].id
}

Below are patterns you’ll commonly use in practice: conditionals, functions, for loops, and dynamic blocks.

# Conditional
resource "azurerm_virtual_machine" "jumpbox" {
vm_size = var.environment == "production" ? "Standard_DS3ads_v5" : "Standard_DS1_v2"
}
# Function - lookup: search for a specific value in a map/list
module "aks" {
...
aks_subnet_name = lookup(var.subnet_map, "app_subnet").name
}
# For loop: recreate locals (local variables) from subnet_map (a map variable), keyed to a nested map of objects
locals {
network_security_groups = {
for key, value in var.subnet_map : key => value.network_security_group
}
}
# Dynamic resource creation
resource "azurerm_network_security_group" "nsg" {
...
dynamic "security_rule" {
for_each = each.value.security_rules
content {
name = security_rule.value.name
priority = security_rule.value.priority
direction = security_rule.value.direction
access = security_rule.value.access
protocol = security_rule.value.protocol
source_port_ranges = security_rule.value.source_port_ranges
destination_port_ranges = security_rule.value.destination_port_ranges
source_address_prefix = security_rule.value.source_address_prefix
destination_address_prefix = security_rule.value.destination_address_prefix
}
}
}
  • 1 Set: A single configuration designs the entire infrastructure environment. This makes it easy to build identical replica environments, but as the number of resources grows, conflicts and management difficulty increase, and module dependencies/maintenance become harder.
  • Multi Set: Agreed-upon domains are defined, and each user takes ownership of a distributed slice of the management scope. Module dependencies are lower and management can be distributed by domain, but the required ordering and overall aggregate structure need to be tracked separately.

Reference Pattern

If 1 Set vs. Multi Set is about who manages which scope, environment separation is about applying the same configuration differently to dev, stg, and prd. The four strategies are not mutually exclusive and are usually combined.

PlantUML Diagram
StrategyState separationCode separationGood fit
Folder structure + modulesFully separate, one backend per directoryDirectory per environment, shared parts in modules/Environments differ substantially, or subscriptions and permissions must be separated too
Per-environment variable files (*.tfvars)Depends on backend configurationShared code, separate valuesDifferences are simple, such as SKU, region, or CIDR
Terraform workspacesState separated per workspace automaticallyFully shared codeShort-lived environments under the same permissions, such as feature validation
GitHub Actions matrixFollows the strategies aboveOnly pipeline execution branchesReviewing plans for several environments at once

An example combining folder structure and variable files:

  • Directorymodules/ Reusable shared modules
    • Directorynetwork/
      • …
    • Directoryaks/
      • …
  • Directoryenvironments/
    • Directorydev/
      • main.tf Calls modules/
      • backend.tf dev-only state location
      • dev.tfvars
    • Directoryprd/
      • main.tf
      • backend.tf prd-only state location
      • prd.tfvars
jobs:
plan:
runs-on: ubuntu-latest
strategy:
matrix:
environment: [dev, prd]
defaults:
run:
working-directory: environments/${{ matrix.environment }}
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform plan -var-file="${{ matrix.environment }}.tfvars" -out=tfplan

Things to watch when choosing:

  • Workspaces are not strong isolation. All workspaces share the same backend and credentials. HashiCorp also notes that workspaces are not appropriate for deployments that require separate credentials and access controls. If prd is managed under a different subscription or permissions, split it into a directory (or a separate root module).
  • Separate apply from plan. The example stops at plan. Running -auto-approve against prd on every push ships changes without review. In this series, plan results are reviewed in the PR through the CommentOps Pipeline before apply.
  • Ideally, environments differ only in variables. If the main.tf files start declaring different resources per environment, first check whether that difference can be expressed as module inputs.

Continue with A CommentOps-based Terraform Pipeline: From Plan to Apply.