민한의 블로그

Terraform-docs 문서화 해보기 본문

인프라/Terraform

Terraform-docs 문서화 해보기

minhan2 2022. 11. 21. 15:59
728x90
반응형

terraform-docs

https://terraform-docs.io/

terraform 자원들을 한눈에 볼수있도록 docs(문서)을 생성하는 툴
terraform 자체도 IaC로써 코드로 관리하기 편리하긴 하지만,
자원이 다양해지고, 환경이 나뉠수록 문서화를 따로 해야하는가 하는 고민이 있었음.
설치가 쉽고, Github Actions로 자동화가 가능하고, 필요한 부분만 옵션으로 문서화가 손쉽게 가능하다는 점이 정말 큰 장점이라고 생각함.

image


brew에서 설치

$ brew sinstall traforram-docs

zsh에서 코드 auto-completion 적용

$ terraform-docs completion zsh > /usr/local/share/zsh/site-functions/_terraform-docs
$ autoload -U compinit && compinit

간단하게 실행해보기

테라폼 레포지토리에 들어와서 실행

$ terraform-docs markdown . > README.md
$ terraform-docs tfvars hcl . > README_VAR.md

아래부터는 설정 추가해보기

필요한 부분만 문서화 하기

terraform-docs를 사용함으로써
사용하고 있는 각 버전들과, 모듈, 리소스, 인풋, 아웃풋을 한곳에서 확인할수 있다는점이 좋았음.
옵션으로 버전, 모듈, 리소스를 제외하고, 인풋, 아웃풋만 문서화를 한다던지, 선택도 가능함
그리고 항상 명령어를 입력할 필요없이, github-actions로 자동화도 가능하다는게 장점.

# example 1: this will only show 'providers'
$ terraform-docs --show providers .

# example 2: this will hide 'inputs' and hide 'providers' and show everything else
$ terraform-docs --hide inputs --hide providers .

아웃풋 파일 위치 정하기

$ pwd
/path/to/module

$ tree .
.
├── docs
│   └── README.md
├── ...
└── main.tf

# this works, relative path
$ terraform-docs markdown table --output-file ./docs/README.md .

# so does this, absolute path
$ terraform-docs markdown table --output-file /path/to/module/docs/README.md .

문서 커스텀하기

생성하고자 하는 문서에 대해서 GO템플릿화(ex- footer,header) 등을 따로 분리해서 원하는 위치로 넣어줄수가 있고, 원하는 값을 직접 넣어줄수도 있음.

$ tree
.
├── examples
│   ├── example-1
│   │   ├── main.tf
│   └── example-2
│       └── main.tf
├── ...
├── main.tf
├── variables.tf
├── ...
└── .terraform-docs.yml

# .terraform-docs.yml
content: |-
  {{ .Header }}

  ## Example

   ```hcl
  {{ include "examples/example-1/main.tf" }}
   ```hcl

  {{ .Inputs }}

  {{ .Outputs }}  

각 옵션들을 config 파일로 만들어서 해서 사용

$ pwd
/path/to/parent/folder

$ tree
.
├── module-a
│   └── main.tf
├── module-b
│   └── main.tf
├── ...
└── .terraform-docs.yml

# executing from parent
$ terraform-docs -c .terraform-docs.yml module-a/

# executing from child
$ cd module-a/
$ terraform-docs -c ../.terraform-docs.yml .

# or an absolute path
$ terraform-docs -c /path/to/parent/folder/.terraform-docs.yml .

Github Action 로 자동화하기

테라폼 레포지토리에 .github/workflows/documentation.yml 파일을 생성하여 아래의 코드를 작성해준다.

name: Generate terraform docs
on:
  - pull_request

jobs:
  docs:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
      with:
        ref: ${{ github.event.pull_request.head.ref }}

    - name: Render terraform docs and push changes back to PR
      uses: terraform-docs/gh-actions@main
      with:
        working-dir: .
        output-file: README.md
        output-method: inject
        git-push: "true"
728x90
반응형
Comments