DDetB.Log
article thumbnail
Published 2023. 8. 13. 02:33
Terraform - State Backends DevOps/Terraform
이 포스팅은 CloudNet@ 팀이 진행하는 테라폼 기초 입문 스터디에 참여하며 ‘테라폼으로 시작하는 IaC’ 책을 기준하여 정리한 글입니다.

State Backends

테라폼은 지속적인 State 데이터를 사용하여 관리하는 리소스를 추적한다. State Backends를 통해 여러 사람이 State 데이터에 액세스하고 해당 인프라 리소스 모음을 협업할 수 있다.

  • 관리 : 지속적인 State 백업을 위해서 local 이외의 저장소가 필요
  • 공유 : 다수의 작업자가 동일한 State로 접근해 프로비저닝하기 위한 공유 스토리지 필요
  • 격리 : 민감한 데이터가 State 파일에 저장될 가능성을 고려하여, 각각의 환경에 따라 접근 권한 제어 필요

Available Backends

  • local: 기본 백엔드로 로컬파일 시스템에 구성
  • remote: Terraform Cloud/Enterprise의 워크스페이스를 의미하며, 1.1.0 부터 remote 백엔드에서 cloud로 명시화
  • azurerm: Azure Blob Storage
  • consul: 하시코프 Consul의 KV를 사용
  • cos: Tencent Cloud Object Storage
  • gcs: Google Cloud Storage
  • http: GET, PST, DELETE를 지원하는 REST 클라이언트 대상
  • Kubernetes: Kubernetes Secret
  • oss: Alibaba Cloud Object Storage Service
  • pg: Postgres Database
  • s3: Amazon S3 버킷을 사용하고, 추가로 Dynamo DB 설정 시 State 잠금 및 일관성 검사 지원

Terraform Cloud(TEC) Backend

하시코프에서 프로비저닝 대상과 별개로 State를 관리할 수 있도록 SaaS 환경인 TFC를 제공. State 관리 기능은 무상.

계정 생성

https://app.terraform.io/

Create a new organization -> org 입력 후 생성

로그인

$ terraform login
Terraform will request an API token for app.terraform.io using your browser.

If login is successful, Terraform will store the token in plain text in
the following file for use by subsequent commands:
    /home/aiden/.terraform.d/credentials.tfrc.json

Do you want to proceed?
  Only 'yes' will be accepted to confirm.

  Enter a value: yes

yes 입력 시 아래와 같이 브라우저에 유저 토큰 생성 화면

이후 생성된 토큰 값 입력

Generate a token using your browser, and copy-paste it into this prompt.

Terraform will store the token in plain text in the following file
for use by subsequent commands:
    /home/aiden/.terraform.d/credentials.tfrc.json

Token for app.terraform.io:
  Enter a value:

토큰 확인

$ cat ~/.terraform.d/credentials.tfrc.json | jq

테스트

$ git clone https://github.com/hashicorp/tfc-getting-started.git
Cloning into 'tfc-getting-started'...
remote: Enumerating objects: 214, done.
remote: Counting objects: 100% (90/90), done.
remote: Compressing objects: 100% (39/39), done.
remote: Total 214 (delta 51), reused 61 (delta 41), pack-reused 124
Receiving objects: 100% (214/214), 53.11 KiB | 7.59 MiB/s, done.
Resolving deltas: 100% (97/97), done.
$ cd tfc-getting-started
$ scripts/setup.sh

--------------------------------------------------------------------------
Getting Started with Terraform Cloud
-------------------------------------------------------------------------

Terraform Cloud offers secure, easy-to-use remote state management and allows
you to run Terraform remotely in a controlled environment. Terraform Cloud runs
can be performed on demand or triggered automatically by various events.

This script will set up everything you need to get started. You'll be
applying some example infrastructure - for free - in less than a minute.

First, we'll do some setup and configure Terraform to use Terraform Cloud.

Press any key to continue (ctrl-c to quit):

실습

https://github.com/Aiden-Yoo/terraform-aws-collaboration 의 샘플 코드 사용

 

GitHub - Aiden-Yoo/terraform-aws-collaboration: [Chapter 7] Collaboration Code Example

[Chapter 7] Collaboration Code Example. Contribute to Aiden-Yoo/terraform-aws-collaboration development by creating an account on GitHub.

github.com

실습 준비

$ git clone https://github.com/aiden-yoo/terraform-aws-collaboration
$ mv terraform-aws-collaboration terraform-aws-collaboration-tom
$ cp -r terraform-aws-collaboration-tom terraform-aws-collaboration-jerry

tom 루트 모듈과 jerry 루트 모듈을 사용해 공통 백엔드 구성과 동작을 확인 → 두 작업자가 동일한 AWS 인프라를 프로비저닝하기를 원하는 상황

기본 상태 각 루트에서 작업

tom 루트 모듈

$ cd terraform-aws-collaboration-tom

$ terraform init
$ terraform plan -var=prefix=dev
$ terraform apply -auto-approve -var=prefix=dev

# 확인
$ terraform workspace list
$ terraform state list
$ ls terraform.tfstate*
$ terraform output

jerry 루트 모듈

$ cd ..
$ cd terraform-aws-collaboration-jerry

# 확인
$ terraform init && terraform plan -var=prefix=dev

=> State가 공유되지 않아 plan시 새로이 프로비저닝 됨을 확인.

TEC를 통해 작업 결과 공유

TFC의 workspaces는 CLI에서의 workspace처럼 테라폼 구성과는 별개로 State를 관리

tom 루트 모듈에 main.tf 파일 수정

terraform {
  cloud {
    organization = "Aiden-org"         # 생성한 ORG 이름 지정
    hostname     = "app.terraform.io"      # default

    workspaces {
      name = "terraform-aws-collaboration"  # 없으면 생성됨
    }
  }
...

실행 및 확인

$ cd ..
$ cd terraform-aws-collaboration-tom

$ terraform init
yes

# 파일내용 확인
ls terraform.tfstate*
cat terraform.tfstate

TEC 웹 콘솔 확인

=> Remote 저장소를 사용함으로써 다수의 사용자가 공통된 Remote 환경의 State를 사용할 수 있음

profile

DDetB.Log

@DDetMok

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!