Terraform 프로젝트: 간단한 EC2 + 보안 그룹
발행: (2025년 12월 5일 오전 07:29 GMT+9)
3 min read
원문: Dev.to
Source: Dev.to
프로젝트 구조
terraform-project/
│── main.tf
│── variables.tf
│── outputs.tf
│── providers.tf
│── terraform.tfvars
│── modules/
│ └── ec2/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
└── README.md
providers.tf
AWS 제공자와 리전을 정의합니다.
terraform {
required_version = ">= 1.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.aws_region
}
variables.tf
모든 입력 변수.
variable "aws_region" {
description = "AWS region"
type = string
default = "us-east-2"
}
variable "instance_type" {
description = "EC2 instance size"
type = string
default = "t2.micro"
}
variable "project_name" {
description = "Tag for resources"
type = string
default = "tf-demo"
}
main.tf
모듈을 호출하고 변수를 전달합니다.
module "ec2_demo" {
source = "./modules/ec2"
instance_type = var.instance_type
project_name = var.project_name
}
outputs.tf
output "ec2_public_ip" {
description = "Public IP of EC2"
value = module.ec2_demo.public_ip
}
output "ec2_id" {
description = "EC2 Instance ID"
value = module.ec2_demo.instance_id
}
terraform.tfvars (선택 입력)
aws_region = "us-east-2"
instance_type = "t2.micro"
project_name = "students-demo"
Module: modules/ec2/main.tf
보안 그룹과 태그가 있는 EC2 인스턴스를 생성합니다.
resource "aws_security_group" "demo_sg" {
name = "${var.project_name}-sg"
description = "Allow SSH"
ingress {
description = "SSH"
from_port = 22
to_port = 22
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"]
}
}
resource "aws_instance" "demo" {
ami = "ami-0c02fb55956c7d316" # Amazon Linux 2 us-east-2
instance_type = var.instance_type
security_groups = [aws_security_group.demo_sg.name]
tags = {
Name = "${var.project_name}-ec2"
}
}
Module: modules/ec2/variables.tf
variable "instance_type" {
type = string
}
variable "project_name" {
type = string
}
Module: modules/ec2/outputs.tf
output "public_ip" {
value = aws_instance.demo.public_ip
}
output "instance_id" {
value = aws_instance.demo.id
}
실행 방법 (학습 단계)
-
Terraform 초기화
terraform init -
구성 검증
terraform validate -
실행 계획 검토
terraform plan -
구성 적용
terraform apply -auto-approve -
출력 값 보기
terraform output -
작업이 끝난 후 인프라 파괴
terraform destroy -auto-approve
학생들이 이 프로젝트를 통해 배우는 내용
| 구성 요소 | 가르치는 내용 |
|---|---|
providers.tf | 제공자 설정 및 버전 제약조건 |
variables.tf | 변수, 타입, 기본값 |
terraform.tfvars | 기본값 재정의 |
main.tf | 모듈 호출 |
modules/ | 실제 운영 설계 |
| EC2 + SG | 간단한 인프라 프로비저닝 |
outputs.tf | 값 내보내기 |
Terraform workflow (init, plan, apply, destroy) | 전체 라이프사이클 관리 |