Terraform을 활용한 자동화 구성 관리(22.04.21)

박민선·2022년 4월 25일
0

Terraform

HCL: Hashicorp Configuration Language

DSL: Domain Specific Language

Workflow

  • 코드 작성(Write()
  • 계획(Plan)
  • 적용(Apply)

프로바이더
https://registry.terraform.io/browse/providers

설치

terraform 설치
https://www.terraform.io/downloads

sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
sudo yum -y install terraform

terraform --version

aws-cli 설치
https://docs.aws.amazon.com/ko_kr/cli/latest/userguide/getting-started-install.html

cd ~
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" 
sudo yum install -y unzip
unzip awscliv2.zip 
sudo ./aws/install

aws --version

aws configure
aws sts get-caller-identity

timedatectl (시간확인)

sudo vi /etc/chrony.conf
(다른 서버 지우고 붙여넣기)
server 3.kr.pool.ntp.org iburst
server 2.asia.pool.ntp.org iburst
server 3.asia.pool.ntp.org iburst

sudo systemctl restart chronyd

timedatectl set-ntp true

timedatectl set-timezone Asia/Seoul

timedatectl

(만약 세팅이 안될 시 수동으로 하는 법)
sudo timedatectl set-ntp false
sudo timedatectl set-time "2022-04-20 10:00:00:00"
sudo timedatectl set-ntp true


구성파일

Terraform Configure File

  • .tf
  • .tf.json: Json 형식

인코딩
Unicode

디렉토리
현재 작업 디렉토리 위치에 따라서 해당 디렉토리의 .tf, .tf.json 모두 읽어서 실행

구성 파일

<BLOCK TYPE> <BLOCK LABEL> ... {
	ARGUMENT
	KEY = VALUE
}

{ } 블록

aws 리소스 참고링크 :
https://registry.terraform.io/providers/hashicorp/aws/latest/docs

테라폼 블록

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.27"
    }
  }

  required_version = ">= 0.14.9"
}
  • aws: 프로바이더의 이름
  • source: 프로바이더의 종류
  • version: 프로바이더의 버전
    - 4.10: 특정 버전
    - ~> 3.12: 특정 버전 이상
    - - > 3.12: 최소 버전

프로바이더 블록(필수)

provider "aws" {
  profile = "default"
  region  = "us-west-2"
}
  • provider "aws": terraform 블록 이름 매칭
    - profile: aws 자격증명 파일의 프로필
    - region

참고
테라폼 리소스 = 앤서블 모듈
테라폼 모듈 = 앤서블 역할

리소스 블록

resource "RESOURCE_TYPE" "NAME" {
  ARGUMENT = VALUE
}
  • RESOURCE_TYPE: 리소스 종료
  • NAME: 리소스 이름(테라폼에서 구분 하기 위한 이름)
  • ARGUMENT: 인자/속성

실행 순서

초기화

terraform init

프로바이더 플러그인 설치

언제?

  • 최초로 프로바이더 설치
  • 프로바이터 버전 업데이트

init 변경 시
ls -a
terraform.lock.hcl 을 삭제 후 재 init
.terraform 파일은 git 업로드 하면 안된다.

포멧팅 (=linting)

terraform fmt

언제?

  • 새로운 파일 작성
  • 기존 파일 변경

terraform.tfstate , terraform.tfstate.backup
파일은 수정 및 git push하면 안된다.

유효성 검증

terraform validate

계획

terraform plan

적용

terraform apply

제거

terraform destroy

상태 확인

  • terraform.tfstate: 현재상태
  • terraform.tfstate.backup: 직전 상태
terraform show
terraform state list
terraform state show aws_instance.app_server

상태 재 동기화

terraform refresh

리소스 생성 순서

  • 의존 관계가 없는 리소스는 병렬로 실행
  • 의존 관계가 있는 경우 의존 관계에 따라서 순서가 정해지게 됨

명시적 의존성

resource "aws_instance" "app_server" {

  depends_on = [
    aws_s3_bucket.app_bucket
  ]
}

https://www.terraform.io/language/meta-arguments/depends_on


입력 변수(Input Variable)

https://www.terraform.io/language/values/variables

variable "image_id" {
  type = string
}

variable "availability_zone_names" {
  type    = list(string)
  default = ["us-west-1a"]
}
  • type:
    • 일반 타입
      - string
         - "app_server"
      - number
         - 1
         - 1.0
      - bool
         - true
         - false
    • 복합 타입
      - list / tuple
         - [a, b, c]
      - map / object
         - {a = abc, b = xyz}
  • default: 기본 값
  • description: 설명
variable abc {
  type = list(string)
  # ["a", "b"]
  type = list(number)
  # [1, 2]
}

변수 값 할당

variable.tf에 default를 설정하지 않았을때

-var 옵션 (우선 순위가 가장 높음)

terraform plan -var "instance_name=xyz"

terraform.tfvars 파일 (가장 많이 쓰는 방식)

terraform.tfvars

instance_name = "xyz"

map(string) 예

variable "aws_availability_zone"{
  description  = "aws AZs"
  type = map(string)
  default = {
    ap-northeast-1 = "ap-northeast-1a"
    ap-northeast-2 = "ap-northeast-2a"
  }
}
tags = {
  AZ = var.aws_availability_zone["ap-northeast-1"]
}
profile
클라우드신생아

0개의 댓글