inblog logo
|
Unchaptered
  • Profile
  • Organization
Terraform

Terraform Linting TFLint 도입하기

unchaptered's avatar
unchaptered
Oct 09, 2024
Terraform Linting TFLint 도입하기
Contents
개요InstallationGet Started점진적인 도입

개요

Terraform 코드를 수정하다 보면 아래와 같은 문법을 수시로 사용해야 합니다.

  • terraform fmt : HCL 문법 상의 오타가 있는지 확인 가능

  • terraform validate : 잘못된 타입의 변수를 전달했거나, 존재하지 않는 프로퍼티에 접근

    했는지 확인 가능

위 문법은 존재하지 않는 타입*인 t99.tiny를 입력하는 경우에는 대응할 수 없습니다.

resource "aws_instance" "example" {
  instance_type = "t99.tiny"

  # ... other codes
}

이를 위해서 TFLint를 사용하면 주요 클라우드 공급사에 대한 파라미터 검증이 가능합니다.
Medium에도 Nayan Tank가 작성한 How to Use TFLint to Check Errors in Your Terraform Code 를 통해서 관련한 설명이 자세히 나와있습니다.

Installation

MacOS를 사용하기 때문에 다음과 같이 TFLint를 설치했습니다

  • TFLint Installation

Get Started

TFLint 사용법도 매우 간단합니다.

  1. Terraform File이 있는 경로에 *.tflint.hcl파일 작성하기

    plugin "terraform" {
        enable = true
        preset = "recommended"
    }
  2. Terraform File이 있는 경로에서 아래 명령어로 TFLint 실행하기

    tflint

만약 TFLint에 정의한 preset을 위반하는 경우가 있다면,
아래와 같이 issue를 출력하면서 프로세스가 닫히게 됩니다

leeminseok@leeui-MacBookPro network % tflint
3 issue(s) found:

Warning: [Fixable] Interpolation-only expressions are deprecated in Terraform v0.12.14 (terraform_deprecated_interpolation)
...

다만 Terraform Module 문서화 자동화에서 언급한 바와 같이,
Terraform File들이 천여개가 넘는 폴더에 흩어져 있는 상황입니다.
따라서 다음과 같은 2가지 문제점이 발생합니다.

  1. *.tflint.hcl 파일을 천여개가 넘는 폴더에 작성하는 것은 무리가 있습니다.

  2. 모든 폴더에 적용된 TFLint는 동일한 preset을 따르도록 하고 싶습니다.

따라서 다음과 같이 간단한 ShellScript 작성해서 해결했습니다.

DIR=$1
if [ -z "$1" ]; then
    echo "[ERROR]./docs.sh DIR 중에서 DIR이 누락되었습니다."
    exit 127
fi

TF_DIRS=$(find "$DIR" -type f -name "*.tf" -exec dirname {} \; | sort -u)
for TF_DIR in $TF_DIRS; do
    cp terraform.tflint.hcl $TF_DIR
    tflint --chdir="$TF_DIR"
done

점진적인 도입

TFLint를 중간에 도입했더니 수천개가 넘는 TFLint 이슈가 출력됩니다.
따라서 당장 이걸 전부 반영하는 것이 물리적으로 불가능한 것 같습니다.
그래서 아래와 같이 로그 파일을 기록하도록 구성하였습니다.

touch terraform.tflint.log

DIR=$1
if [ -z "$1" ]; then
    echo "[ERROR]./docs.sh DIR 중에서 DIR이 누락되었습니다."
    exit 127
fi

TF_DIRS=$(find "$DIR" -type f -name "*.tf" -exec dirname {} \; | sort -u)
for TF_DIR in $TF_DIRS; do
    cp terraform.tflint.hcl $TF_DIR
    tflint --chdir="$TF_DIR" >> terraform.tflint.log
done

만약 처음부터 TFLint를 도입할 생각이며 엄격하게 개발을 할 예정이라면,
다음과 같이 TFLint Issue가 보고되면 바로 ShellScript도 중단되게 할 수 있습니다.

set -e

DIR=$1
if [ -z "$1" ]; then
    echo "[ERROR]./docs.sh DIR 중에서 DIR이 누락되었습니다."
    exit 127
fi

TF_DIRS=$(find "$DIR" -type f -name "*.tf" -exec dirname {} \; | sort -u)
for TF_DIR in $TF_DIRS; do
    cp terraform.tflint.hcl $TF_DIR
    tflint --chdir="$TF_DIR"
done
Share article

Unchaptered

RSS·Powered by Inblog