콘텐츠로 이동

CommentOps 기반 Terraform Pipeline: Plan에서 Apply까지

Interactive Diagram

새 탭 ↗
  • az login 기반 Azure CLI 로그인
  • terraform provisioning 환경은 OIDC 기반 인증(Azure User Assigned Managed Identity 기반)을 사용
Terminal window
export ARM_CLIENT_ID=<clientId>
export ARM_SUBSCRIPTION_ID=<subscriptionId>
export ARM_TENANT_ID=<tenantId>

providers.tf가 위치한 디렉토리에서 실행하며, tfvars는 선택 사용이다(TACOS tool 기반 digger project 관리).

Terminal window
### terraform provider install
terraform init
### plan 검증 및 생성
terraform plan
### 생성된 plan 기준으로 적용
terraform apply

Local 환경에서는 plugin cache를 설정해 terraform provider를 symbolic link 방식으로 실행한다.

Terminal window
> cat ~/.terraformrc
plugin_cache_dir = "~/.terraform.d/plugin-cache/"

module 및 stacks 기반 구조로 관리한다.

  • digger.yml
  • 디렉터리modules
    • cache
    • container-registry
    • cosmosdb
    • kubernetes
    • network
    • sql-database
    • sql-server
    • vault
    • vm-ubuntu
  • 디렉터리stacks
    • 디렉터리dev
      • backend.tf
      • configurations
      • data.tf
      • main.tf
      • outputs.tf
      • providers.tf
      • variables.tf

Terraform code repository 기반 Infra 배포의 주요 흐름은 다음과 같다.

Infra Provisioning Flow

TACOS(Terraform Automation & Collaboration Tools) 활용

섹션 제목: “TACOS(Terraform Automation & Collaboration Tools) 활용”

TACOS는 Terraform의 협업과 자동화를 위한 도구들을 통칭하는 용어다.

  • Pull Request는 원래 개발 feature/hotfix에 대한 code review 및 변경 이력 관리를 위해 사용된다.
  • TACOS tool을 통합하면 Terraform code에 대한 review뿐 아니라 변경 내역에 대한 이력 관리까지 가능해진다.
  • 주요 관리 내용
    • terraform plan 실행 및 예상 결과
    • terraform apply 실행 및 적용된 내역
    • (Optional) 기타 API를 활용한 Infra 변경에 따른 예상 요금 시뮬레이션
Capability/Toolterraform Cloudterraform EnterpriseScalrEnv0Spacelift
ComplianceISO 27001, SOC 2ISO 27001, SOC 2❓SOC 2ISO 27001, SOC 2
GitLab Integration✅✅✅✅✅
HostingSaaSSaaS, On-PremSaaS, On-PremSaaSSaaS
Policy as CodeSentinelSentinelOPAOPAOPA
Pricing ModelUnpredictable in highers tiersStill figuring it outMixedMixedPer capabilities and users
Private Agents✅✅✅✅✅
Private Module Registry✅✅✅✅✅ - with CI/CD
RBAC✅✅✔️ - hierarchical✔️ - hierarchical✔️ - also extensible with policies
Remote operations CLI✅✅✅✅✅
Remote operations VCS/GitOps✅✅✅✅✅
SLA99.9% for highers tierN/A❓❓❓
SSO✅ - only in high paid tiers✅✅ - only in high paid tiers✅ - only in high paid tiers✅
Secrets ManagementInternalVault integratedInternalInternal, AWS, GCP, AzureInternal, also file based
Short lived environments support❌❌❌✅✅
State Management✅✅✅✔️ - only hidden state✅ - also external
terraform Provider✅✅✅✅✅
Webhooks✅✅✅✅✅

Atlantis는 GitHub 등 Git 솔루션의 PR 동작과 긴밀하게 연동되는 도구로, 별도 K8s 환경에 Self-hosted 형태로 구성해서 사용한다. GitHub Flow를 따라 동작한다.

Atlantis 동작 흐름

  • 장점
    • GitHub Comment 화면에서 Terraform 관련 기능(Plan, Apply) 관리 가능
    • 단일 MR만 생성되게 하여 인프라 환경을 일관되게 관리
  • 단점
    • 동시에 여러 개 MR이 존재할 수 없어 작업자가 다수일 경우 병목 발생
    • 다양한 브랜치 전략 수립이 상대적으로 어려움
    • Self-hosted 환경이 별도로 필요함

Digger Cloud라는 public service로 제공되며, GitHub Action Pipeline에 통합해 주로 사용한다.

  • 장점
    • 보안성: OIDC와 OPA를 통한 RBAC를 지원해 사용자별로 다른 권한 부여 가능
    • 비용 효율성: 기존 CI 도구를 그대로 활용해 추가 컴퓨팅 리소스가 필요 없음
    • 유연성: Apply-on-merge 방식과 기존 방식을 모두 지원
    • CI와 Backend 분리: Terraform 작업을 수행하는 CI 도구와 작업을 조율하는 Orchestrator가 분리되어 있어 기존 CI 도구의 이점을 그대로 활용 가능
  • 단점
    • 커뮤니티 규모: Atlantis에 비해 사용자와 레퍼런스 규모가 상대적으로 작음
    • 성능: Backend에서 모든 워크플로우를 처리하는 Atlantis에 비해 작업 속도 면에서 다소 떨어질 수 있음
  1. 실행 환경
    • Atlantis: 단일 VM에서 Terraform 실행
    • Digger: 기존 CI 인프라 활용, 각 작업마다 새로운 Docker 컨테이너 사용
  2. 보안
    • Digger: 클라우드 계정이나 민감한 상태 데이터에 직접 접근하지 않음
    • Atlantis: Terraform을 직접 실행하므로 더 많은 접근 권한 필요
  3. 서버 관리
    • Digger: 대부분의 경우 자체 호스팅 불필요
    • Atlantis: 일반적으로 자체 서버 유지 관리 필요
  4. 비용
    • Digger: 기존 CI 컴퓨팅 리소스 활용으로 비용 효율적
    • Atlantis: 별도의 강력한 VM 인스턴스 필요
  5. 적용 시점
    • Digger: 병합 전/후 적용 모두 지원
    • Atlantis: 주로 병합 전 적용 지원
  6. 접근 제어
    • Digger: OPA 정책을 통한 유연한 RBAC
    • Atlantis: 서버 옵션을 통한 GitHub 역할 기반 접근 제어

우리는 기존 CI 인프라를 그대로 활용할 수 있고 별도 서버 유지보수 부담이 없는 Digger를 최종 채택했다.

TACOS 기반 Infra Provisioning 실전 구성

섹션 제목: “TACOS 기반 Infra Provisioning 실전 구성”

GitHub Pull Request 기반 CommentOps로 Infra Provisioning Plan/Apply 이력을 관리하고, Infracost API 연계로 Cost Estimation을 함께 관리한다.

Public access가 가능한 GitHub Hosted Runner 및 API 기반으로 구성한다.

Public Access 기반 Digger 통합

Private Access 기반 Digger 통합 구성

섹션 제목: “Private Access 기반 Digger 통합 구성”

GitHub Self-hosted Runner 및 Digger backend self managed service 기반으로 구성한다.

Private Access 기반 Digger 통합

digger.yml로 Digger workflow를 설정한다. 기본 plan/apply workflow에 infracost api 호출 step을 추가한 예시다.

digger.yml
projects:
- name: platform-infra-dev
dir: stacks/dev
workflow: with-infracost
workflows:
with-infracost:
plan:
steps:
- init
- run: terraform output --raw aks_kube_config > .kubeconfig || true
- plan
- run: infracost breakdown --path=. | tee -a $DIGGER_OUT
apply:
steps:
- init
- run: terraform output --raw aks_kube_config > .kubeconfig || true
- apply
auto_merge: false
pr_locks: true
  • Pull Request 생성 기반 Infra 배포 Plan 검증

    PR 기반 Plan 검증

  • Pull Request 검토 및 Comment 기반 Infra 배포 실행

    Comment 기반 Apply 실행

Terraform Code 분석 기반, Infracost API 호출 결과 예시다.

Project: main
Name Monthly Qty Unit Monthly Cost
module.kubernetes_module.azurerm_kubernetes_cluster.aks
└─ default_node_pool
├─ Instance usage (Linux, pay as you go, Standard_d2as_v5) 730 hours $77.38
└─ os_disk
└─ Storage (P10, LRS) 1 months $19.71
module.cache_redis_module.azurerm_redis_cache.cache_redis
└─ Cache usage (Basic_C0) 1 nodes $20.44
module.cache_redis_module.azurerm_private_endpoint.pe
├─ Private endpoint 730 hour $7.30
├─ Inbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
└─ Outbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
module.cosmosdb_mongo_module.azurerm_private_endpoint.pe
├─ Private endpoint 730 hour $7.30
├─ Inbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
└─ Outbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
module.sqlserver_module.azurerm_private_endpoint.pe
├─ Private endpoint 730 hour $7.30
├─ Inbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
└─ Outbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
module.vault_module.azurerm_private_endpoint.pe
├─ Private endpoint 730 hour $7.30
├─ Inbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
└─ Outbound data processed (first 1PB) Monthly cost depends on usage: $0.01 per GB
module.acr_app_module.azurerm_container_registry.acr
├─ Registry usage (Basic) 30 days $5.00
├─ Storage (over 10GB) Monthly cost depends on usage: $0.10 per GB
└─ Build vCPU Monthly cost depends on usage: $0.0001 per seconds
module.acr_base_module.azurerm_container_registry.acr
├─ Registry usage (Basic) 30 days $5.00
├─ Storage (over 10GB) Monthly cost depends on usage: $0.10 per GB
└─ Build vCPU Monthly cost depends on usage: $0.0001 per seconds
module.cache_redis_module.azurerm_private_dns_zone.pdz
└─ Hosted zone 1 months $0.50
module.cosmosdb_mongo_module.azurerm_private_dns_zone.pdz
└─ Hosted zone 1 months $0.50
module.sqlserver_module.azurerm_private_dns_zone.pdz
└─ Hosted zone 1 months $0.50
module.vault_module.azurerm_private_dns_zone.pdz
└─ Hosted zone 1 months $0.50
module.sqldb_module.azurerm_mssql_database.sqldb
├─ Compute (serverless, GP_S_Gen5_2) Monthly cost depends on usage: $0.59 per vCore-hours
├─ Storage 2 GB $0.27
├─ Long-term retention (LRS) Monthly cost depends on usage: $0.0295 per GB
└─ PITR backup storage (LRS) Monthly cost depends on usage: $0.12 per GB
OVERALL TOTAL $159.00
*Usage costs can be estimated by updating Infracost Cloud settings, see docs for other options.
──────────────────────────────────
27 cloud resources were detected:
∙ 13 were estimated
∙ 14 were free
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━━━━━┓
┃ Project ┃ Baseline cost ┃ Usage cost* ┃ Total cost ┃
┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━━━╋━━━━━━━━━━━━━╋━━━━━━━━━━━━┫
┃ main ┃ $159 ┃ - ┃ $159 ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━┻━━━━━━━━━━━━┛

Terraform Graph

Terraform으로 구성하는 Azure Resource 배포 Pattern에서 이어서 본다.