๐Ÿ”ง DevOps

IaC

Infrastructure as Code

A method of defining and managing infrastructure as code. Uses Terraform, Pulumi, and CloudFormation.

Detailed Explanation

IaC (Infrastructure as Code) is an approach to defining and managing infrastructure as code. Instead of manually clicking through a console, you provision infrastructure such as servers, networks, and databases with declarative or imperative code. Version control, code review, and automated testing become possible, so infrastructure management becomes like software development.

Core Principles of IaC

  • Version control: Track all infrastructure changes with Git
  • Idempotency: Running the same code multiple times produces the same result
  • Reproducibility: The same environment can be recreated at any time
  • Documentation: The code itself serves as infrastructure documentation
  • Automation: Integrates with CI/CD pipelines

Declarative vs. Imperative

  • Declarative: Defines the desired end state. Terraform, CloudFormation
  • Imperative: Defines the steps to perform. Ansible, Bash scripts

Major IaC Tools

  • Terraform: Multi-cloud IaC tool (HashiCorp)
  • Pulumi: Defines infrastructure in programming languages
  • AWS CloudFormation: AWS-native IaC
  • Azure Bicep: DSL for Azure ARM templates
  • Ansible: Configuration management and provisioning

Code Example

Terraform - Defining AWS Infrastructure

# main.tf - AWS VPC์™€ EC2 ์ธ์Šคํ„ด์Šค
terraform {
  required_version = ">= 1.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket         = "my-terraform-state"
    key            = "prod/terraform.tfstate"
    region         = "ap-northeast-2"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

provider "aws" {
  region = var.region

  default_tags {
    tags = {
      Environment = var.environment
      ManagedBy   = "Terraform"
    }
  }
}

# VPC
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.1.0"

  name = "${var.project}-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["ap-northeast-2a", "ap-northeast-2c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24"]

  enable_nat_gateway = true
  single_nat_gateway = var.environment != "production"

  tags = {
    Project = var.project
  }
}

# Security Group
resource "aws_security_group" "web" {
  name        = "${var.project}-web-sg"
  description = "Security group for web servers"
  vpc_id      = module.vpc.vpc_id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${var.project}-web-sg"
  }
}

# EC2 Instance
resource "aws_instance" "web" {
  count = var.instance_count

  ami           = data.aws_ami.amazon_linux.id
  instance_type = var.instance_type
  subnet_id     = module.vpc.private_subnets[count.index % length(module.vpc.private_subnets)]

  vpc_security_group_ids = [aws_security_group.web.id]

  root_block_device {
    volume_size = 20
    volume_type = "gp3"
    encrypted   = true
  }

  tags = {
    Name = "${var.project}-web-${count.index + 1}"
  }
}

# Data source
data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }
}

variables.tf - Variable Definitions

# variables.tf
variable "region" {
  description = "AWS region"
  type        = string
  default     = "ap-northeast-2"
}

variable "project" {
  description = "Project name"
  type        = string
}

variable "environment" {
  description = "Environment (development, staging, production)"
  type        = string

  validation {
    condition     = contains(["development", "staging", "production"], var.environment)
    error_message = "Environment must be development, staging, or production."
  }
}

variable "instance_type" {
  description = "EC2 instance type"
  type        = string
  default     = "t3.micro"
}

variable "instance_count" {
  description = "Number of EC2 instances"
  type        = number
  default     = 2
}

terraform.tfvars - Per-Environment Values

# environments/prod.tfvars
region         = "ap-northeast-2"
project        = "myapp"
environment    = "production"
instance_type  = "t3.medium"
instance_count = 4

Terraform CLI Commands

# ์ดˆ๊ธฐํ™” - provider ๋‹ค์šด๋กœ๋“œ
terraform init

# ๊ณ„ํš - ๋ณ€๊ฒฝ์‚ฌํ•ญ ๋ฏธ๋ฆฌ ํ™•์ธ
terraform plan -var-file=environments/prod.tfvars

# ์ ์šฉ - ์‹ค์ œ ์ธํ”„๋ผ ์ƒ์„ฑ/์ˆ˜์ •
terraform apply -var-file=environments/prod.tfvars

# ์ƒํƒœ ํ™•์ธ
terraform state list
terraform state show aws_instance.web[0]

# ํŠน์ • ๋ฆฌ์†Œ์Šค๋งŒ ์ ์šฉ
terraform apply -target=aws_instance.web

# ์‚ญ์ œ
terraform destroy -var-file=environments/prod.tfvars

# ํฌ๋งทํŒ… ๋ฐ ๊ฒ€์ฆ
terraform fmt -recursive
terraform validate

Practical Conversation Example

Junior DevOps
"I built the infrastructure in the AWS console, and now I need to create an identical staging environment. Do I have to click through and build it all again?"
Senior DevOps
"Building things manually is error-prone and takes a long time. If you codify it with Terraform, you can create the same environment in 5 minutes with `terraform apply -var-file=staging.tfvars`."
Junior DevOps
"I'm afraid I'll accidentally wipe out production when changing the infrastructure."
Senior DevOps
"That's exactly the advantage of IaC. You check the changes in advance with `terraform plan`, get a code review through a PR, and then apply. If you store the state file in S3 and lock it with DynamoDB, you can also prevent multiple people from running apply at the same time and corrupting things."

Cautions

State File Security

Terraform state files store sensitive information such as passwords and keys in plaintext. Be sure to enable S3 encryption and access restrictions.

Plan Review Is Required

Always check the plan output before apply. Review it carefully, especially if it includes `destroy` or `replace`.

State Locking

If multiple people run terraform apply at the same time, the state can become corrupted. Set up locking with DynamoDB or similar.

Drift Management

Manual changes in the console cause the code and the actual state to diverge. Periodically detect drift with `terraform plan`.

Learn More