Overview
이번 주는 CloudNet@에서 진행 중인 Terraform 101 Study(T101) 6주차로, 실습 범위는 Terraform을 단순한 로컬 도구가 아닌, 팀 협업을 위한 Terraform Cloud(TFC) 중심으로 확장하는 과정이었다.
특히 TFC + GitHub 연동을 통해 실질적인 CI/CD 기반 IaC 운영 환경 구성을 경험하였고, 테라폼의 상태 파일을 안전하게 원격에서 관리하고, UI 기반 실행 및 승인 흐름까지 따라가보는 시간이 되었다.
이번 주 핵심 실습 주제
- Terraform Cloud(TFC) 기반 백엔드 설정 및 원격 실행
- Variable Set을 활용한 민감 정보 관리 및 UI 기반 변수 선언
- Execution Mode 차이점(Local vs Remote) 이해 및 활용
- TFC + GitHub 연동 (VCS Provider) 및 OAuth 설정
- Pull Request 기반 자동 Plan 트리거 및 Auto-Apply 실습
- GitHub Actions가 없이도 Terraform 실행 자동화 경험
- 실습 후 리소스 및 TFC 설정까지 안전하게 정리 및 제거하는 과정
모든 실습내용은 아래의 github에 정리하였다.
https://github.com/somaz94/t101-study
GitHub - somaz94/t101-study: t101-study
t101-study. Contribute to somaz94/t101-study development by creating an account on GitHub.
github.com
Terraform Cloud (TFC)
TFC
워크플로 구성 환경 제공, Github Action 보다 자유도는 낮지만 VCS연동, 변수 구성, RBAC, 원격 실행 환경 등의 기능 활용가능하다.
다음 저장소 포크 : https://github.com/terraform101/terraform-aws-tfc-workflow
- terraform 블록에 지정된 cloud 백엔드의 organization 의 값을 소유한 이름으로 변경
terraform login
MyGit=<>
MyGit=somaz94
git clone https://github.com/$MyGit/terraform-aws-tfc-workflow
cd terraform-aws-tfc-workflow
MyTfcOrg=<각자 자신의 TFC 조직명>
MyTfcOrg=somaz-org
sed -i -e "s/<MY-ORG>/$MyTfcOrg/g" main.tf
git add main.tf
git commit -m "init"
git push
terraform init
Terraform Cloud/Enterprise의 워크스페이스 실행 모드 구분
- `테라폼으로 시작하 IaC ` 책 참고
Local | Remote | |
실행 위치 | 테라폼 실행 환경(로컬 작업자 환경)에서 프로비저닝 수행 | Terraform Cloud/Enterprise 환경에서 독립된 원격 실행 환경 부여 |
입력 변수 | 로컬 환경의 terraform.tfvars를 읽고 실행 시 입력 가능 | UI에서 작성된 변수를 읽고 *.auto.tfvars 형태의 구성에서 입력 받음 |
Apply 승인 | 로컬 작업자가 `yes` 입력 | CLI 수행한 경우 `yes` 입력 또는 UI/API로 승인 |
TFC 생성 워크스페이스에 Execution Mode를 Remote로 했기 때문에 Error가 발생한다.
terraform plan
Running plan in Terraform Cloud. Output will stream here. Pressing Ctrl-C
will stop streaming the logs, but will not stop the plan running remotely.
Preparing the remote plan...
To view this run in a browser, visit:
https://app.terraform.io/app/somaz-org/terraform-aws-tfc-workflow/runs/run-ifokyBvYiBwGuWFh
Waiting for the plan to start...
Terraform v1.5.6
on linux_amd64
Initializing plugins and modules...
╷
│ Error: No value for required variable
│
│ on variables.tf line 1:
│ 1: variable "prefix" {
│
│ The root module input variable "prefix" is not set, and has no default
│ value. Use a -var or -var-file command line argument to provide a value for
│ this variable.
╵
Operation failed: failed running terraform plan (exit 1)
따라서 TFC 환경과 같이 중앙 실행 관리 환경을 사용하면 민감한 정보를 공유하거나 로컬에 저장하지 않고 안전하게 사용할 수 있다.
`Create variable set` 후 `+ADD variable로 입력`
- Prefix : Type(Terraform variable), Key(prefix), value(사용자 닉네임)
- Access Key ID : Type(Environment variable), Key(AWS_ACCESS_KEY_ID), value(자신의 값)
- Secret Access Key : Type(Environment variable), Key(AWS_SECRET_ACCESS_KEY), value(자신의 값), Sensitive 선택
`plan` 후 `apply`
terraform plan
Running plan in Terraform Cloud. Output will stream here. Pressing Ctrl-C
will stop streaming the logs, but will not stop the plan running remotely.
Preparing the remote plan...
To view this run in a browser, visit:
https://app.terraform.io/app/somaz-org/terraform-aws-tfc-workflow/runs/run-jWpqzfKLwdXr3xT7
Waiting for the plan to start...
Terraform v1.5.6
on linux_amd64
Initializing plugins and modules...
data.aws_ami.ubuntu: Refreshing...
data.aws_ami.ubuntu: Refresh complete after 1s [id=ami-09cb01cc28a9bd950]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
+ create
Terraform will perform the following actions:
# aws_eip.hashicat will be created
+ resource "aws_eip" "hashicat" {
...
`apply` 후에 바로 yes 를 하면안된다. 그럼 아래와 같은 화면을 볼 수 있다.
`See details` 를 클릭하면 아래와 같은 화면을 볼 수 있다.
`apply` 완료 되면, 아래와 같이 Resource를 볼 수 있다.
리소스 삭제
terraform destroy -auto-approve
리소스 삭제가 완료되면 TFC에서도 사라진다.
TFC 권한 관리
Standard plan 이상 필요로 skip 한다.
TFC + VCS 연계
VCS와 직접 통합되어 별도 워크플로 작성 없이도 풀 리퀘스트에 대한 Plan 결과를 확인할 수 있으며 지정된 브랜치에 병합이 발생하면 테라폼을 실행하는 자동화된 구성이 가능하다.
지원되는 VCS는 아래와 같다.
- Github.com / Github.com (OAuth) / Github Enterprise
- Gitlab.com / Gitlab EE와 CE
- Bitbucket Cloud / Bitbucket Server
- Azure DevOps Server / Azure DevOps Services
여기서는 Github.com 와 연동해본다 - [Docs]
- TFC Org → [Settings] → [Version Control] 탭의 Provider ⇒ [Add a VCS provider] 클릭 : Github.com (Custom) 선택 후 → [register a new OAuth Application] 클릭
- 아래 내용 입력 → 하단 [Register application] 클릭
On GitHub, register a new OAuth Application. Enter the following information:
Application name: Terraform Cloud (somaz-org)
Homepage URL: https://app.terraform.io
Application description: Any description of your choice
Authorization callback URL: https://app.terraform.io/auth/4e92098c-1f79-44a9-af4f-2bbeda0366a1/callback
대상 VCS와의 인증 및 권한 처리가 완료 되었으므로 다음 과정을 통해 워크스페이스에 VCS를 연계, 워크스페이스는 Admin 권한으로 수행한다.
- 워크스페이스 선택 → Setting → Version Control 선택 ⇒ [Connect to version control] 클릭
1. Version control workflow 선택
2. 연동된 VCS목록에서 [My Github.com] 선택
3. 포크된 저장소 선택
4. Confirm changes
- Apply Method : [Auto Apply]
5. VCS Triggers
-
- Automatic Run Triggering : [Always trigger runs 선택]
- VCS branch(main 입력)
- Pull Request(Automatic… 체크)
워크스페이스와 VCS간 최초 연동되면 마지막 커밋내용을 기반으로 Run이 실행된다.
[Run] 메뉴로 이동해 깃허브에 의해 트리거링된 정보를 확인하고 Apply를 실행한다.
`main.tf` 파일 수정 : terraform.cloud 블록 주석 처리 ← VCS 연동으로 더 이상 필요하지 않다.
terraform {
# cloud {
# organization = "somaz-org"
# hostname = "app.terraform.io" # default
# workspaces {
# name = "terraform-aws-tfc-workflow"
# }
# }
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
tfc-workflow 브랜치 생성, 커밋, 푸시
git branch -M tfc-workflow
git add .
git commit -m "tfc workflow"
git push origin HEAD
자신의 github 에서 PR 생성 → Merge pull request : Confirm
TFC에서 생성된 리소스 삭제 : TFC 워크스페이스 Setting → Destruction and Delete ⇒ Queue destroy plan 로 생성된 리소스 삭제
실습 완료 후 최종 삭제
- TFC Workspace 삭제
- TFC Provider 삭제
- Github Repo 삭제
- 로컬에 Repo 디렉터리 삭제
- OAuth Application 삭제
- (옵션) 임시로 AWS IAM 생성 했을 경우, AWS IAM 계정 삭제
마무리
이번 스터디에서는 Terraform을 로컬 개발 환경에서의 IaC 도구 수준을 넘어, 팀 내에서 안정적으로 협업하고 배포할 수 있는 Terraform Cloud의 기능과 VCS 연동 워크플로우를 직접 구성해보았다.
특히 기억에 남는 포인트는 다음과 같다.
- Terraform Cloud를 통해 상태 파일을 안전하게 원격에서 관리
- 민감한 변수는 Variable Set을 통해 보호하면서도 UI에서 손쉽게 관리 가능
- GitHub PR을 통해 자동 Plan 실행 및 Apply 승인 프로세스까지 확립
- TFC와 GitHub 연동을 통해 추가적인 GitHub Actions 없이도 CI처럼 자동 실행 가능
TFC는 단순히 백엔드 역할을 넘어서 협업 중심의 IaC 플랫폼으로서 강력한 기능을 제공하며, 향후 팀 단위 IaC 운영 시 꼭 고려해볼만한 솔루션이라는 확신이 들었다.
Terraform Cloud는 팀을 위한 IaC의 시작점이다.
Reference
https://developer.hashicorp.com/terraform/cloud-docs/vcs/github
'교육, 커뮤니티 후기 > T101(Terraform 101 Study) 스터디' 카테고리의 다른 글
T101(Terraform 101 Study) 5주차 (0) | 2023.09.26 |
---|---|
T101(Terraform 101 Study) 4주차 (0) | 2023.09.22 |
T101(Terraform 101 Study) 3주차 (0) | 2023.09.17 |
T101(Terraform 101 Study) 2주차 (0) | 2023.09.09 |
T101(Terraform 101 Study) 1주차 (0) | 2023.08.28 |