Terraform を使うときに記法やお作法を共通化してベストプラクティスに近付けるために TFLint を導入すると便利❗️
最近 TFLint を導入する機会があったので作業ログをまとめる📝
TFLint をセットアップする
TFLint のセットアップは macOS だと Homebrew を使えば簡単〜
今回は TFLint v0.47.0 を前提にする.
$ brew install tflint $ tflint --version TFLint version 0.47.0 + ruleset.terraform (0.4.0-bundled)
TFLint を実行する
基本的には tflint
コマンドを実行すれば OK👌
該当する Warning があるとだーっと表示される.
$ tflint 10 issue(s) found:
もしモジュールを使ってて modules/
ディレクトリ直下も TFLint の対象にする場合は --recursive
オプションを使う.
$ tflint --recursive
TFLint にどんなルールがあるのか
ちょうど最近改善を担当することになった Terraform プロジェクトに TFLint を実行してみたところ Warning が 400件 も出てきた🔥
$ tflint --recursive 400 issue(s) found: (中略)
出てきた Warning をまとめるとほとんどは以下の5種類だった.
- Warning: [Fixable] Interpolation-only expressions are deprecated in Terraform v0.12.14 (terraform_deprecated_interpolation)
- Warning: [Fixable] variable "xxx" is declared but not used (terraform_unused_declarations)
- Warning: `xxx` variable has no type (terraform_typed_variables)
- Warning: terraform "required_version" attribute is required (terraform_required_version)
- Warning: Missing version constraint for provider "aws" in `required_providers` (terraform_required_providers)
現時点だと TFLint の Terraform ルールセットには「16種類」のルールが実装されている.その中でもデフォルトでは Recommended
として「10種類」のルールが有効化されている.
TFLint の設定ファイル .tflint.hcl
で以下のように preset = "all"
と書くとすべてのルールを有効化できる.
plugin "terraform" { enabled = true preset = "all" }
今度は --config
オプションで .tflint.hcl
を指定して実行すると,Warning と Notice が 620件 に増えた🔥
$ tflint --recursive --config $(pwd)/.tflint.hcl 620 issue(s) found: (中略)
個別にルールを無効化する
個別にルールを無効化する場合は .tflint.hcl
にルールごとに enabled = false
と書けば ok👌
rule "terraform_required_version" { enabled = false } rule "terraform_required_providers" { enabled = false }
自動的に修正する
出てきた Warning を自動的に修正する場合は --fix
オプションを使う.ただし,自動的に修正できないルールもあるので,最終的には一つずつ確認しながら修正していくのが良いと思う.
$ tflint --recursive --fix
TFLint を GitHub Actions で動かす
TFLint を GitHub Actions で動かす場合は「Setup TFLint Action」を使えば簡単に導入できる❗️
TFLint は --format compact
オプションも対応しているため,GitHub Actions の Problem Matchers を使ってプルリクエストに直接コメントできる❗️
\( 'ω')/ これは便利〜
name: TFLint on: push: branches: - master pull_request: branches: - master jobs: tflint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup TFLint uses: terraform-linters/setup-tflint@v3 with: tflint_version: v0.47.0 - name: Show version run: tflint --version - name: Run TFLint run: tflint --recursive --config $(pwd)/.tflint.hcl --format compact
TFLint Ruleset for terraform-provider-aws も導入する
TFLint の Plugin として TFLint Ruleset for terraform-provider-aws を導入すると AWS Provider に特化したルールを追加できる❗️以下のように .tflint.hcl
に plugin を追加して tflint --init
コマンドを実行すれば OK👌
plugin "aws" { enabled = true version = "0.24.3" source = "github.com/terraform-linters/tflint-ruleset-aws" }
こっちは特に Warning は出なかった💨