Terraform 개요

Terraform 개요

1 Terraform이란?

Terraform은 HashiCorp에서 개발한 Infrastructure as Code(IaC) 도구로, 선언형 구문을 사용하여 클라우드 인프라를 자동화할 수 있습니다.

2 Terraform의 주요 특징

  • 멀티 클라우드 지원 (AWS, GCP, Azure, Kubernetes 등)
  • 선언적 코드 작성 방식
  • 상태 파일을 활용한 인프라 관리
  • 강력한 모듈화 지원

3 Terraform 설치하기

Windows

choco install terraform

Linux & macOS

brew install terraform

설치가 완료되면 terraform -v 명령어로 확인합니다.


2️⃣ Terraform 기본 개념

1 프로비저닝이란?

프로비저닝(Provisioning)은 시스템이나 서비스를 배포 및 설정하는 프로세스를 의미합니다.

2 Terraform 구성 요소

  • Providers: 클라우드 서비스 제공자(AWS, Azure 등)
  • Modules: 재사용 가능한 코드 조각
  • State 파일: 현재 인프라 상태 저장 (terraform.tfstate)

3 HCL(HashiCorp Configuration Language)

Terraform에서 사용되는 선언형 언어로, JSON과 유사한 구조를 가집니다.

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

3️⃣ Terraform 기본 명령어

1 terraform init

프로젝트 초기화 및 필요한 Provider 다운로드

terraform init

2 terraform plan

적용 전 변경 사항을 확인

terraform plan

3 terraform apply

Terraform 코드를 실행하여 인프라를 배포

terraform apply

4 terraform destroy

배포된 인프라 삭제

terraform destroy

4️⃣ Terraform 코드 작성 실습

1 AWS EC2 인스턴스 생성

main.tf

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

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = "t2.micro"
}

2 변수 사용하기

variables.tf

variable "instance_type" {
  default = "t2.micro"
}

main.tf

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = var.instance_type
}

5️⃣ Terraform 상태 파일 및 백엔드

1 Terraform State란?

Terraform은 배포된 인프라의 현재 상태를 terraform.tfstate 파일에 저장합니다.

2 원격 상태 저장

Terraform 상태 파일을 로컬이 아닌 S3, Git 등 원격 저장소에 보관할 수 있습니다.

terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "terraform.tfstate"
    region = "us-east-1"
  }
}

6️⃣ Terraform 모듈화

1 Terraform 모듈이란?

모듈(Module)은 반복 사용 가능한 Terraform 코드 블록입니다.

2 모듈을 사용한 예제

main.tf

module "ec2" {
  source        = "./modules/ec2"
  instance_type = "t2.micro"
}

modules/ec2/main.tf

resource "aws_instance" "example" {
  ami           = "ami-12345678"
  instance_type = var.instance_type
}

7️⃣ Terraform 고급 기능

1 Terraform Workspace

Workspace를 활용하여 여러 환경(개발, 운영)을 관리할 수 있습니다.

terraform workspace new dev
terraform workspace select dev

2 Terraform Provisioner

Provisioner는 인스턴스 생성 후 추가 설정을 자동화할 때 사용됩니다.

resource "aws_instance" "example" {
  provisioner "remote-exec" {
    inline = [
      "sudo apt update",
      "sudo apt install nginx -y"
    ]
  }
}

8️⃣ Terraform 배포 자동화

1 Terraform과 CI/CD

Terraform을 GitHub Actions, Jenkins 등과 연동하여 자동 배포할 수 있습니다.

2 GitHub Actions 예제

name: Terraform CI/CD
on:
  push:
    branches:
      - main
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v1

      - name: Terraform Init
        run: terraform init

      - name: Terraform Apply
        run: terraform apply -auto-approve

RSS Feed
마지막 수정일자