목차
개요
Terraform을 사용하는 초기에는 Local에서 혼자 사용하거나 여러 명이서 사용한다고 하더라도 규모가 작기 때문에 큰 무리가 없다. 그러나, 규모가 점점 늘어나고, 관리해야 하는 리소스가 복잡해지고, 협업을 고민하게 되면 다양한 방법을 찾아보게 될 것이다.
Atlantis는 Terraform의 Pull Request를 자동화해주는 오픈소스 솔루션으로, Pull Request(Gitlab에서는 Merge Request)가 발생하면 자동으로 terraform (또는 terragrunt) plan을 해주고, apply도 comment로 가능하도록 지원해준다. 이를 사용하면 모두 동일한 버전의 형상을 사용할 수 있고, comment와 approve, notification 기능을 모두 활용할 수 있어서 협업에 보다 효과적으로 사용할 수 있어 일전에 구성했던 내용을 메모해두고자 한다.
Workflow
1. Terraform 코드 개발 후 Gitlab에 Push (※ Master가 아닌 별도 Branch)
2. 작업한 Branch를 Main Branch로 Merge Request
3. Merge Request가 수행되면 작업한 Branch를 기준으로 Terraform Plan이 수행
(※ 실제 수행은 repository root directory의 .atlantis.yaml을 참조)
4. 수행 결과 확인 후 특이사항이 없으면 atlantis apply Comment를 통해 apply 적용
5. apply 정상 완료 후 Branch Merge
Atlantis 구성
공식홈페이지에 내용이 잘 정리되어 있다. 이에 Gitlab 설치, atlantisbot 등의 절차는 생략하고 Deploy 위주로 내용을 작성한다. (공식홈페이지 참조)
Dockerfile
atlantis에서 제공하는 Docker Image를 사용해도 되나, terragrunt를 사용하고자 별도로 Dockerfile을 구성하였다.
아래 Dockerfile build 전에 terragrunt를 별도로 다운받아야 한다.
FROM runatlantis/atlantis
# copy a terraform binary of the version you need
COPY terragrunt /usr/local/bin/terragrunt
Docker 기동
--repo-config-json은 atlantis.yaml 파일의 workflow 및 apply requirements를 커스텀하게 설정하기 위한 옵션으로, 필요하지 않을 경우에는 빼도 된다. (상세 내용 참조) --restart=unless-stopped 옵션은 Docker 단독 기동 시 필요한 옵션으로, Docker Container가 계속 지속될 수 있도록 해준다.
docker run --restart=unless-stopped -d -p 4141:4141 [docker-image-name] server \
--gitlab-hostname="https://[url]" \
--gitlab-user="atlantisbot" \
--gitlab-token="[token]" \
--gitlab-webhook-secret="[secret]" \
--repo-allowlist=* \
--repo-config-json='{"repos":[{"id":"/.*/", "allowed_overrides":["apply_requirements","workflow"], "allow_custom_workflows":true}]}'
Configure Webhook
기타 모든 환경구성이 끝나고 나면, 아래의 방법을 통해 Webhook을 세팅한다.
>> Repository 좌측 바 하단의 Settings > Webhooks 클릭
>> 아래와 같이 URL 및 Secret token 정보 입력 (※ 상세 내용은 공식 도큐먼트 참조)
>> 트리거 선택 (Push events, Comments, Merge request events) 후 Save changes 클릭.
>> 설정 완료 후, 하기의 Members 메뉴로 이동 > atlantisbot을 member에 추가 (Maintainer)
atlantis.yaml
repository root directory에 아래와 같이 구성한다.
version: 3
projects:
- dir: terragrunts/[project1]/
workflow: terragrunt
- dir: terragrunts/[project2]/
workflow: terragrunt
workflows:
terragrunt:
plan:
steps:
- env:
name: TERRAGRUNT_TFPATH
command: 'echo "terraform${ATLANTIS_TERRAFORM_VERSION}"'
- run: terragrunt plan -no-color -out $PLANFILE
apply:
steps:
- env:
name: TERRAGRUNT_TFPATH
command: 'echo "terraform${ATLANTIS_TERRAFORM_VERSION}"'
- run: terragrunt apply -no-color $PLANFILE
기타
권한 부여는 Terraform의 방식을 따라간다. 기본적으로 멀티 어카운트 관리를 하는 경우가 많으므로, AssumeRole 방식으로 Terraform 실행권한 부여가 권장되며 사용도 용이하다.