PRODUCTION LAB — `user_data` 사용 (베스트 프랙티스)

발행: (2026년 3월 19일 AM 12:09 GMT+9)
3 분 소요
원문: Dev.to

Source: Dev.to

개요

전통적인 워크플로우:

Terraform → SSH → install nginx

대신 인스턴스가 부팅 시 스스로 구성하도록 할 수 있습니다:

Terraform → EC2 boots → user_data runs automatically

이 접근 방식은 SSH 접근 및 키 관리가 필요하지 않게 합니다.

Terraform 설정 (main.tf)

provider "aws" {
  region = "us-east-2"
}

# -------------------------------------------------
# Get latest Amazon Linux 2 AMI
# -------------------------------------------------
data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

# -------------------------------------------------
# Security Group (HTTP only, no SSH)
# -------------------------------------------------
resource "aws_security_group" "web_sg" {
  name = "userdata-sg"

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

  # ❗ No SSH (port 22 removed)

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

# -------------------------------------------------
# EC2 Instance (no key pair, no SSH)
# -------------------------------------------------
resource "aws_instance" "web" {
  ami           = data.aws_ami.amazon_linux.id
  instance_type = "t2.micro"

  vpc_security_group_ids = [aws_security_group.web_sg.id]

  # -------------------------------------------------
  # User data (runs at boot)
  # -------------------------------------------------
  user_data =  /var/www/html/index.html
  EOF

  tags = {
    Name = "userdata-lab"
  }
}

설정 배포

mkdir terraform-userdata
cd terraform-userdata

# Create the file and paste the above code
touch main.tf

# Initialise and apply
terraform init
terraform apply -auto-approve

적용이 완료되면 Terraform 출력이나 AWS 콘솔에서 인스턴스의 퍼블릭 IP를 찾아 브라우저에 입력합니다:

http://

다음과 같은 화면이 표시됩니다:

Welcome from Terraform User Data

부팅 중에 AWS가 user_data 스크립트를 실행하며, 이 스크립트는:

  1. Apache(httpd)를 설치
  2. 서비스를 시작
  3. 재부팅 시 자동 시작하도록 설정
  4. 간단한 HTML 페이지 생성

SSH 연결 없이 모두 수행됩니다.

기능 비교

기능프로비저너user_data
SSH 필요 여부아니오
키 필요 여부아니오
실행 시점생성 후부팅 시
프로덕션 적합성❌ 피함✅ 표준
속도느림빠름
신뢰성중간높음

프로덕션에서 user_data를 사용하는 이유

  • 인스턴스 초기화 중 자동 실행
  • SSH 불필요, 공격 표면 및 운영 오버헤드 감소
  • 높은 신뢰성 및 확장성, 임시 프로비저너에 비해 우수

전형적인 프로덕션 흐름:

Terraform → create EC2
        → EC2 boots
        → user_data runs automatically
        → application ready

프로비저너는 학습 및 테스트에 유용하지만, user_data가 실제 프로덕션 환경에서 사실상의 표준입니다.

0 조회
Back to Blog

관련 글

더 보기 »

대규모 Terraform + 고급 개념

markdown !Aisalkyn Aidarovahttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.c...