공부하면서/Terraform

[T1012] 6주차 - 협업 (관리)

omelette master 2023. 8. 11. 00:03
해당 내용은 T1012 스터디에 나온 내용과 '테라폼으로 시작하는 IaC' 책을 기준으로 정리 했습니다

* 5주차는 강사초빙의 시간이였어서 별도로 올리지 않았습니다


협업의 유형 예시

유형1 (scp, 압축, NAS 등)

자신이 작성한 코드를 수동으로 협업 대상에게 공유

인원이 늘어날수록 코드 동기화에 문제가 생긴다 -> 각자 코드에 대해 병합이 어려움!

 

유형2 (형상관리도구, 중앙 저장소 도입)

형상관리 시스템을 통해 여러 사용자가 동일한 코드를 공유 하여 작업 가능

-> 코드 변경 이력과 롤백도 가능

테라폼 코드와 결과물(state)이 같은 저장소에 저장

코드 수정과 테라폼 실행이후 commit & push를 안하여 state 공유가 안될수도 있음

그러기 위해서 원격 백엔드설정을 진행하여 테라폼 실행시 나오는 자동으로 업로드 해야함

유형3 (유형 2와 동일, 저장소 분리)

테라폼 코드 관리를 위한 저장소와 state 저장소를 분리하여 완성된 코드를 공유하고

state는 중앙 관리되어 테라폼 실행하면 원격 state의 상태를 확인 하고 수행한다

7.1 형상 관리 도구

  • 버전관리 시스템(VCS) 혹은 형상관리시스템(SCM)

SVN: 중앙 저장소에서 코드와 히스토리를 관리하는 방식

Git: 분산형 관리 시스템으로 작업 환경에서도 별도로 코드 history를 관리하고 중앙 저장소와 동기화 할수 있는 도구

7.1.1 깃

깃을 사용하면 중앙저장소와 코드를 동기화 하지 않아도 같은 파일을 여러명이 작업할수 있다

로컬 저장소(자신의 작업환경) 와 원격 저장소에 저장이 가능

7.1.2 리모트 저장소 - 깃허브 (해당 실습에서는 github으로 진행)

준비물: github 계정, github access token

personal access token(PAT) 생성하기!

7.2 코드 관리

실습을 위한 git 코드를 fork 진행

 

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

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

github.com

더보기
  • fork 한 저장소는 원본저장소와 연결되어 있고 이후 변경사항을 원본저장소에 적용하는 요청(pull request)이 가능

공유 제외 대상

  • 코드 파일 공유 시 깃 관리 대상 제외 → .gitignore 정의
    • .terraform 디렉터리 : init 실행 시 작성되므로 제외
    • .tfstate 파일 : 프로비저닝 결과 데이터 소스 정보, 민감 데이터가 포함, 다른 사용자가 같은 State 파일을 사용하는 경우 인프라 불합치 유발
    • tfvars 파일 : 프로비저닝 시 적용할 변수 값을 보관하는 파일로, 작업자 마다 별도 변수 사용
    • 시크릿 파일 : 인프라 구성에 필요한 시크릿 정보 파일
    • terraformrc 파일 : 작업자의 CLI 설정 파일
더보기
# .gitignore
# Local .terraform directories
**/.terraform/*

# .tfstate files
*.tfstate
*.tfstate.*

# Crash log files
crash.log
crash.*.log

# Exclude all .tfvars files, which are likely to contain sensitive data, such as
# password, private keys, and other secrets. These should not be part of version 
# control as they are data points which are potentially sensitive and subject 
# to change depending on the environment.
*.tfvars
*.tfvars.json

# no creds
*.pem

# Ignore override files as they are usually used to override resources locally and so
# are not checked in
override.tf
override.tf.json
*_override.tf
*_override.tf.json

# Include override files you do wish to add to version control using negated pattern
# !example_override.tf

# Include tfplan files to ignore the plan output of command: terraform plan -out=tfplan
# example: *tfplan*

# Ignore CLI configuration files
.terraformrc
terraform.rc

7.3 State 백엔드

구성 목적으로 3가지를 들수 있다

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

구성 가능한 백엔드로는 다음과 같다

remote Terraform Cloud/Enterprise의 워크스페이스를 의미
1.1.0 부터 remote 백엔드에서 cloud로 명시
local 기본 백엔드로 로컬 파일 시스템에 구성
azurerm Azure 클라우드의 Blob storage
consul 하시코프 Consul의 KV(Key-value store)를 사용
cos Tencent 클라우드의 Object Storage
gcs Google 클라우드 Storage
http GET, POST, DELETE 를 지원하는 REST 클라이언트
kubernetes Kubernetes Secret으로 저장
oss Alibaba 클라우드 Object Storage 서비스
pg postgresql 에 저장
s3 AWS S3 버킷을 추가 하고, DynamoDB 설정시 State 잠금 및 일관성 검사

7.3.1 Terraform Cloud (TFC) 백엔드

 

Terraform Cloud by HashiCorp

 

app.terraform.io

라이선스 정책

내가 사용할 Free plan은 최대 사용자 5명, 리소스 500개, 보안기능(SSO, Sentinel/OPA로 policy 사용)

TFC 가입 후 셋팅

더보기
free account를 클릭하여 가입할수 있다
이후 조직을 생성해준다 Create a new Organization
_ 이나 - 를 이용하여 고유 조직 이름을 생성
# 이후 CLI에서 로그인을 해본다
terraform login

---
kkyoung@DESKTOP-26MI22N:/mnt/d/study/workspaces/terraform-aws-collaboration-jerry$ 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/kkyoung/.terraform.d/credentials.tfrc.json

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

  Enter a value: yes
  ---
  
  # 이후 브라우저로 넘어간다
T101 Study라는 이름의 토큰 생성

이후 토큰을 입력 해주면 된다

# 이후 토큰을 입력 해주면 된다

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/kkyoung/.terraform.d/credentials.tfrc.json

Token for app.terraform.io:
  Enter a value: #토큰입력!!!
# 로그인이 완료되면 다음과 같이 출력된다

Retrieved token for user kkyoung96


---------------------------------------------------------------------------------

                                          -
                                          -----                           -
                                          ---------                      --
                                          ---------  -                -----
                                           ---------  ------        -------
                                             -------  ---------  ----------
                                                ----  ---------- ----------
                                                  --  ---------- ----------
   Welcome to Terraform Cloud!                     -  ---------- -------
                                                      ---  ----- ---
   Documentation: terraform.io/docs/cloud             --------   -
                                                      ----------
                                                      ----------
                                                       ---------
                                                           -----
                                                               -


   New to TFC? Follow these steps to instantly apply an example configuration:
# 샘플 테스트 할수 있는 방법을 출력 해준다
   $ git clone https://github.com/hashicorp/tfc-getting-started.git
   $ cd tfc-getting-started
   $ scripts/setup.sh

7.3.2 백엔드 구성

TFC의 workspaces는 CLI의 Workspace(링크)처럼 테라폼 구성과는 별개로 state를 관리하는 단위

terraform {
  cloud {
    organization = "<MY_ORG_NAME>"         # 생성한 ORG 이름 지정
    hostname     = "app.terraform.io"      # default

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

내가 만든 kkyoung_org의 collaboration에 기록

# main.tf 수정후 init으로 초기화 진행

terraform init

---

kkyoung@DESKTOP-26MI22N:/mnt/d/study/workspaces/terraform-aws-collaboration-tom$ terraform init

Initializing Terraform Cloud...
Do you wish to proceed?
  As part of migrating to Terraform Cloud, Terraform can optionally copy your
  current workspace state to the configured Terraform Cloud workspace.

  Answer "yes" to copy the latest state snapshot to the configured
  Terraform Cloud workspace.

  Answer "no" to ignore the existing state and just activate the configured
  Terraform Cloud workspace with its existing state, if any.

  Should Terraform migrate your existing state?

  Enter a value: yes

생성된 workspace인 collaboration
terraform init을 통해 마이그레이션된 state 업로드 정보
plan, apply 등의 작업시 이렇게 상황이 기록된다

7.3.3 백엔드 활용

  • TFC의 좋은 점으로 State 잠금기능이 있으며 프로비저닝 수행시 동일한 state 접근을 못하게 lock 상태로 전환 해준다