Programming/IaC

[IaC] Terraform state -상태파일공유

Hayley Shim 2023. 10. 28. 17:48

안녕하세요. CloudNet@ Terraform Study를 진행하며 해당 내용을 이해하고 공유하기 위해 작성한 글입니다. 도서 ‘Terraform: Up & Running(By Yevgeniy Brikman)’ 의 내용 및 스터디 시간 동안 언급된 주요 내용 위주로 간단히 정리했습니다.

  • 상태 파일은 배포할 때마다 변경되는 프라이빗 API private API로, 오직 테라폼 내부에서 사용하기 위한 것입니다.
  • 상태 파일은 직접 편집하거나 직접 읽는 코드로 작성해서는 안됩니다.

상태 파일 확인

 
# 배포 
$ terraform init && terraform plan && terraform apply -auto-approve # 상태 파일 확인 : JSON 형식 
$ ls cat terraform.tfstate | jq
... 
"serial": 2, 
...
 
# 배포 
$ terraform plan && terraform apply -auto-approve# 상태 파일 비교 : 백업 파일 생성됨 
$ ls terraform.tfstate* 
terraform.tfstate        terraform.tfstate.backup$ diff terraform.tfstate terraform.tfstate.backup 
<   "serial": 4, 
--- 
>   "serial": 2, 
...

상태파일공유

  • 여러 명의 팀원이 파일에 공통으로 액세스할 수 있게 하는 가장 일반적인 방법은 파일을 깃과 같은 버전 관리 시스템에 두는 것이지만 테라폼 상태 파일을 버전 관리 시스템에 저장하는 것은 아래와 같은 이유로 부적절합니다.
  1. 수동오류 : 팀의 누군가가 이전 버전의 상태 파일로 테라폼을 실행하고 그 결과 실수로 이전 버전으로 롤백하거나 이전에 배포된 인프라를 복제하는 문제 발생 가능
  2. 잠금 : 대부분의 버전 관리 시스템은 여러 명의 팀 구성원이 동시에 하나의 상태 파일에 terraform apply 명령을 실행하지 못하게 하는 잠금 기능을 제공하지 않음
  3. 시크릿 : 테라폼 상태 파일의 모든 데이터는 평문으로 저장되는데 특정 테라폼 리소스에 중요한 데이터를 저장해야 할 때 문제 발생

팀 단위에서 테라폼 운영 시 문제점

  1. 상태 파일 잠금 Locking state files
  • 잠금 기능 없이 두 팀원이 동시에 테라폼 실행 시 여러 테라폼 프로세스가 상태 파일을 동시에 업데이트하여 충돌 가능(경쟁 상태 race condition)

지원되는 원격 백엔드

  • 원격 백엔드를 사용하면 상태 파일을 원격 공유 저장소에 저장할 수 있습니다.
  • AWS S3, Azure Blob Storage, Google Cloud Storage, Consul, Postgres database 등 — 링크
  • 잠금 : apply 실행 시 테라폼은 자동으로 잠금을 활성화, -lock-timout=<TIME> 로 대기 시간 설정 지정 가능

S3/DynamoDB 생성

S3 버킷 생성

  • bucket : s3 버킷의 이름. aws의 다른 모든 고객들과 겹치지 않게끔 고유한 값 사용
  • prevent_destroy: create_before_destroy 설정에 이은 두번째 수명 주기 설정(lifecycle setting). prevent_destroy를 true로 설정하면 terraform destroy를 실행하는 것 같이 리소스를 삭제하려고 시도하는 경우 테라폼이 오류와 함께 종료됨
  • versioning : s3 버킷에 버전 관리를 활성화하여 버킷의 파일이 업데이트될 때마다 새 버전을 만듦. 이를 통해 언제든지 이전 버전으로 돌릴 수 있음
  • server_side_encryption_configuration : s3 버킷에 기록된 모든 데이터에 서버 측 암호화를 설정함. 이렇게하면 s3에 저장될 때 상태 파일이나 그 파일에 포함된 어떤 시크릿이라도 암호화됨
 
# 배포
$ terraform init && terraform plan && terraform apply -auto-approve
$ terraform state list
aws_s3_bucket.hayleys3bucket
aws_s3_bucket_versioning.hayleys3bucket_versioning# S3 버킷 확인
$ aws s3 ls
2022-10-23 22:21:48 hayley-t101study-tfstate

DynamoDB 테이블 생성

  • DynamoDB는 아마존의 분산형 키-값 저장소이며 분산 잠금 시스템에 필요한 강력한 읽기 일관성 및 조건부 쓰기를 지원합니다.
  • 테라폼에서 DynamoDB 잠금을 사용하기 위해서는 LockID 라는 기본 키가 있는 테이블을 생성해야됩니다.
 
# 배포
$ terraform plan && terraform apply -auto-approve
$ terraform state list
aws_dynamodb_table.hayley-dynamodbtable
aws_s3_bucket.hayleys3bucket
aws_s3_bucket_versioning.hayleys3bucket_versioning# DynamoDB 테이블 생성 확인 
$ aws dynamodb list-tables --output text
TABLENAMES      terraform-locks

DEV 환경 설정

# 배포
$ terraform **init** && terraform **plan** && terraform **apply** -auto-approve
$ terraform **state list
$ ls terraform.tfstate***
terraform.tfstate        terraform.tfstate.backup# 출력된 EC2 퍼블릭IP로 cul 접속 확인
$ MYIP=$(terraform output -raw hayley-ec2_public_ip)
$ while true; do curl --connect-timeout 1  http://$MYIP/ ; echo "------------------------------"; date; sleep 1; done

DEV 환경에 Backend 적용

  • bucket : 사용할 s3 버킷 이름
  • key : 테라폼 상태 파일을 저장할 s3 버킷 내으 ㅣ파일 경로
  • region : s3 버킷이 있는 aws 리전
  • dynamodb_table : 잠금에 사용할 DynamoDB 테이블
  • encrypt : true로 설정하면 테라폼 상태가 s3 디스크에 저장될 때 암호화됨.
 
  • remote state 저장소로 s3를 사용하고 dynamoDB를 통해 lock 관리를 합니다.
$ terraform initInitializing the backend...
Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous "local" backend to the
  newly configured "s3" backend. No existing state was found in the newly
  configured "s3" backend. Do you want to copy this state to the new "s3"
  backend? Enter "yes" to copy and "no" to start with an empty state.Enter a value: yesuccessfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v4.29.0Terraform has been successfully initialized!You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.$ ls terraform.tfstate*
terraform.tfstate               terraform.tfstate.backups

STG 환경 설정

# 배포
$ terraform init
$ terraform plan && terraform apply -lock-timeout=60s -auto-approve
$ terraform state list
$ ls terraform.tfstate*
terraform.tfstate        terraform.tfstate.backup

 

 

blog migration project

written in 2022.10.23

https://medium.com/techblog-hayleyshim/iac-terraform-state-faa4ee8cd66e

'Programming > IaC' 카테고리의 다른 글

[IaC] Terraform modules  (0) 2023.10.28
[IaC] Terraform state -상태파일격리  (0) 2023.10.28
[IaC] GKE configuration  (0) 2023.10.28
[IaC] Terraform Syntax-GCP  (0) 2023.10.28
[IaC] Terraform Syntax-AWS  (1) 2023.10.28