Terraform으로 인프라 코드화 (IaC)


Terraform은 HashiCorp에서 만든 Infrastructure as Code(IaC) 도구입니다. AWS, GCP, Azure 등 클라우드 인프라를 코드로 정의하고 버전 관리할 수 있습니다.



언제 사용하나요?



  • 클라우드 인프라 자동 프로비저닝

  • 개발/스테이징/프로덕션 환경 일관성 유지

  • 인프라 변경사항 추적 및 롤백

  • 멀티 클라우드 환경 관리



설치 및 시작


# macOS
brew install terraform

# Linux
wget https://releases.hashicorp.com/terraform/1.6.0/terraform_1.6.0_linux_amd64.zip
unzip terraform_1.6.0_linux_amd64.zip
sudo mv terraform /usr/local/bin/

# 버전 확인
terraform version


기본 구조


# main.tf - AWS EC2 인스턴스 생성
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}

provider "aws" {
region = "ap-northeast-2" # 서울 리전
}

resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"

tags = {
Name = "WebServer"
Environment = "Development"
}
}


변수 사용


# variables.tf
variable "instance_type" {
description = "EC2 인스턴스 타입"
type = string
default = "t2.micro"
}

variable "environment" {
description = "배포 환경"
type = string
}

variable "allowed_ports" {
description = "허용할 포트 목록"
type = list(number)
default = [80, 443]
}

# 사용
resource "aws_instance" "web" {
instance_type = var.instance_type
tags = {
Environment = var.environment
}
}

# terraform.tfvars
instance_type = "t2.small"
environment = "production"


Output 정의


# outputs.tf
output "instance_public_ip" {
description = "EC2 퍼블릭 IP"
value = aws_instance.web.public_ip
}

output "instance_id" {
value = aws_instance.web.id
}

# 다른 모듈에서 참조 가능


기본 명령어


# 초기화 (프로바이더 다운로드)
terraform init

# 실행 계획 확인
terraform plan

# 변경사항 적용
terraform apply

# 리소스 삭제
terraform destroy

# 상태 확인
terraform state list
terraform state show aws_instance.web

# 포맷팅
terraform fmt

# 유효성 검사
terraform validate


AWS VPC + EC2 예시


# VPC 생성
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"

tags = {
Name = "main-vpc"
}
}

# 서브넷
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = "10.0.1.0/24"
availability_zone = "ap-northeast-2a"
map_public_ip_on_launch = true
}

# 보안 그룹
resource "aws_security_group" "web" {
vpc_id = aws_vpc.main.id

ingress {
from_port = 80
to_port = 80
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"]
}
}

# EC2 인스턴스
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.instance_type
subnet_id = aws_subnet.public.id
vpc_security_group_ids = [aws_security_group.web.id]
}


모듈 사용


# 모듈 구조
modules/
ec2/
main.tf
variables.tf
outputs.tf

# 모듈 호출
module "web_server" {
source = "./modules/ec2"

instance_type = "t2.micro"
environment = "dev"
}

# 공개 모듈 사용
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0.0"

name = "my-vpc"
cidr = "10.0.0.0/16"
}


상태 파일 원격 저장


# S3 백엔드 설정
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "ap-northeast-2"
dynamodb_table = "terraform-lock"
encrypt = true
}
}


주의사항



  • terraform.tfstate는 민감 정보 포함 - 암호화 필수

  • 팀 사용 시 원격 백엔드 + 잠금 설정

  • plan 결과 반드시 검토 후 apply

  • .terraform/ 디렉토리는 gitignore