Terraform: 인프라를 코드로 관리하기
콘솔에서 버킷을 손으로 만들면 누가 언제 무엇을 바꿨는지 남지 않습니다. Terraform은 만들 리소스를 파일에 적고, 실제 상태와 비교해 차이만 반영합니다. 공고 16건(17%)이 Terraform·IaC를 적습니다. Terraform 1.17.2와 AWS provider 6.73.0으로 S3 흉내 서버(X08)에 버킷을 만들었습니다.
# 데이터 레이크 버킷 2개(raw, curated)와 버전 관리, 오래된 raw 파일 정리 규칙을 코드로 정의합니다.
# endpoints 블록만 지우면 실제 AWS에 같은 리소스가 만들어집니다(그때는 실제 자격 증명 필요).
terraform {
required_providers {
aws = { source = "hashicorp/aws", version = "~> 6.0" }
}
}
provider "aws" {
region = "ap-northeast-2"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_requesting_account_id = true
s3_use_path_style = true
endpoints { s3 = "http://localhost:5055" } # 로컬 S3 흉내 서버(moto)
}
variable "env" { default = "dev" }
locals {
layers = ["raw", "curated"]
}
resource "aws_s3_bucket" "lake" {
for_each = toset(local.layers)
bucket = "shop-${var.env}-${each.key}"
tags = { layer = each.key, owner = "data-eng" }
}
resource "aws_s3_bucket_versioning" "lake" {
for_each = aws_s3_bucket.lake
bucket = each.value.id
versioning_configuration { status = "Enabled" }
}
resource "aws_s3_bucket_lifecycle_configuration" "raw_expire" {
bucket = aws_s3_bucket.lake["raw"].id
rule {
id = "expire-raw-after-90-days"
status = "Enabled"
filter {}
expiration { days = 90 }
}
}
output "buckets" { value = [for b in aws_s3_bucket.lake : b.bucket] }
plan → apply
terraform init
terraform plan
# aws_s3_bucket.lake["curated"] will be created
# aws_s3_bucket.lake["raw"] will be created
# aws_s3_bucket_lifecycle_configuration.raw_expire will be created
# aws_s3_bucket_versioning.lake["curated"] will be created
# aws_s3_bucket_versioning.lake["raw"] will be created
Plan: 5 to add, 0 to change, 0 to destroy.
terraform apply
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
buckets = ["shop-dev-curated", "shop-dev-raw"]
plan은 바꿀 내용을 보여 주기만 하고, apply가 실제로 만듭니다. PR에 plan 결과를 붙여 리뷰받고 병합 뒤에 apply하는 것이 보통의 흐름입니다(X03). var.env만 바꾸면 같은 코드로 dev·prod 버킷을 따로 만듭니다.
누가 콘솔에서 바꿨다면
# 콘솔(여기서는 boto3)에서 raw 버킷의 버전 관리를 끔
콘솔에서 누가 raw 버전 관리를 끔: Suspended
terraform plan
# aws_s3_bucket_versioning.lake["raw"] will be updated in-place
~ status = "Suspended" -> "Enabled"
Plan: 0 to add, 3 to change, 0 to destroy.
terraform apply → Apply complete! Resources: 0 added, 3 changed, 0 destroyed.
terraform plan -detailed-exitcode → 종료 코드 0 (코드와 실제가 같음)
terraform destroy → Destroy complete! Resources: 5 destroyed.
코드와 실제가 달라진 것(드리프트)을 plan이 찾아냈고, apply로 코드 상태로 되돌렸습니다. 매일 plan -detailed-exitcode를 돌려 종료 코드가 2(차이 있음)면 알리는 식으로 감시합니다. 이 실습에서는 버킷 두 개도 "수정"으로 함께 나왔는데, 흉내 서버가 일부 속성을 실제 AWS와 다르게 돌려주는 것으로 보입니다. 원인은 확인하지 않았습니다.
💡
terraform init이 내려받은 AWS provider는 734MB였습니다..terraform/폴더와 상태 파일(terraform.tfstate)은 Git에 올리지 않습니다. 상태 파일에는 리소스 정보가 그대로 들어 있어, 팀에서는 S3 같은 원격 저장소에 두고 잠금을 겁니다.
Terraform은 "만들 것을 적고 → plan으로 차이를 보고 → apply로 반영"합니다. 콘솔에서 바뀐 것도 plan이 드러냅니다.