/인프라/Practical IaC with Terraform: From Module Design to State Management
InfrastructureTerraformIaC

Practical IaC with Terraform: From Module Design to State Management

Click-ops infrastructure cannot be reproduced. Defining infrastructure as code with Terraform enables version control, code review, and automation.

Practical IaC with Terraform: From Module Design to State Management

Why You Need IaC

Infrastructure created by clicking around cannot be reproduced. Defining infrastructure as code with Terraform enables version control, code review, and automation.

Project Directory Structure

CODE
terraform/
├── environments/
│   ├── prod/
│   │   ├── main.tf
│   │   └── terraform.tfvars
│   └── staging/
└── modules/
    ├── vpc/
    ├── eks/
    └── rds/

Module Design

HCL
# modules/vpc/main.tf
resource "aws_vpc" "main" {
  cidr_block           = var.cidr_block
  enable_dns_hostnames = true

  tags = merge(var.common_tags, {
    Name = "${var.project}-${var.environment}-vpc"
  })
}

variable "cidr_block" {
  type    = string
  default = "10.0.0.0/16"

  validation {
    condition     = can(cidrhost(var.cidr_block, 0))
    error_message = "유효한 CIDR 형식이어야 합니다."
  }
}

Remote State Management

HCL
terraform {
  backend "s3" {
    bucket         = "my-company-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "ap-northeast-2"
    encrypt        = true
    dynamodb_table = "terraform-state-lock"
  }
}
Bash
# State 잠금 테이블 생성
aws dynamodb create-table \
  --table-name terraform-state-lock \
  --attribute-definitions AttributeName=LockID,AttributeType=S \
  --key-schema AttributeName=LockID,KeyType=HASH \
  --billing-mode PAY_PER_REQUEST

CI/CD Integration

YAML
name: Terraform
on:
  pull_request:
    paths: ['terraform/**']

jobs:
  plan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init
      - run: terraform fmt -check -recursive
      - run: terraform validate
      - run: terraform plan -out=tfplan

Practical Tips

Never commit tfstate files to git (.gitignore)

CODE
*.tfstate
*.tfstate.backup
.terraform/

Masking sensitive variables

HCL
variable "db_password" {
  type      = string
  sensitive = true
}

Terraform is not just a tool. It is a cultural shift that changes how your team operates infrastructure.

References: Official Docs

The primary source for the behavior, configuration, and errors covered in this post is the official documentation below. Check there for version-specific options and exact behavior.

확인 정보
✦ ✦ ✦
편집 검토 · Editorial Review

Nodelog는 모든 콘텐츠의 내용과 출처를 공개 전에 검토합니다. 환경(OS·버전)에 따라 결과가 달라질 수 있는 기술 정보는 공식 문서와 함께 확인하며, 검토 기준과 정정 원칙은 편집 정책에서 안내합니다. 오류를 발견하시면 이메일로 제보해 주세요 — 확인 후 신속히 정정합니다.

편집 책임 · Nodelog 기술 편집팀·발행 · ·업데이트 ·
관련 공식 문서Terraform 공식 문서

Comments

Be the first to comment.