3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Terraform] TFコードのリソース関係をグラフで表現する方法

Last updated at Posted at 2025-03-30

前書き

Terraformコードが長くなると、リソース間の関係が分かりづらくなることもあります。そのため、リソース間の依存関係をグラフで可視化することが非常に有用です。この記事では、Terraformコードをグラフとして可視化する方法について、いくつかの方法を紹介します。

方法1. terraform graph

Terraformには、リソース間の依存関係をグラフとして出力する terraform graph コマンドが組み込まれています。このコマンドを使って、リソース間の依存関係を可視化することができます。

1-1. Terraformの設定ファイルを準備

まず、Terraformで作業しているディレクトリに移動し、適切なTerraformコード(.tfファイル)があることを確認します。

1-2. terraform graph コマンドを実行

以下のコマンドを実行して、依存関係をDOT形式で出力します。

terraform cli
terraform graph > graph.dot

このコマンドにより、graph.dot というファイルが生成されます。DOT形式は、グラフを表現するためのフォーマットです。

1-3. dotファイルを画像に変換

次に、Graphvizツールを使って、graph.dot をPNGなどの画像に変換します。Graphvizは、DOT形式を視覚的なグラフに変換するツールです。

  • Graphvizのインストール
cli
# macOS:
brew install graphviz
# Ubuntu:
sudo apt install graphviz
  • DOTファイルを画像に変換
    以下のコマンドで、graph.dot をPNG形式に変換できます。
cli
dot -Tpng graph.dot -o graph.png

これで、graph.png という画像ファイルが生成されます。この画像には、Terraformリソース間の依存関係が可視化されています。ただし、リソースが多いと見にくいという欠点があります。

方法2. terraform-docs

terraform-docsは、Terraformコードから自動的にドキュメントを生成するツールです。依存関係の詳細な視覚化には直接使えませんが、モジュールやリソースの構成を文書化するために有用です。

2-1. インストール

cli
brew install terraform-docs

2-2. 使用方法

cli
terraform-docs markdown . > README.md

これにより、TerraformのリソースやモジュールのドキュメントをMarkdown形式で生成することができます。

方法3. terrascan

terrascanは、Terraformコードの静的解析を行うツールで、セキュリティやベストプラクティスに基づいたレポートを生成するために使用されます。依存関係の可視化にも役立つことがありますが、主にセキュリティ監査のツールとして使われます。

3-1. インストール

cli
brew install terrascan

3-2. 使用方法:

cli
terrascan scan -i terraform -p .

方法4. terraform graph beautifier

該当リポジトリはこちらです。
terraform-graph-beautifier

4-1. インストール

cli
go install github.com/pcasteran/terraform-graph-beautifier@v0.2.0

4-2. 使用方法:

cli
terraform graph | terraform-graph-beautifier \
    --exclude="module.root.provider" \
    --output-type=cyto-html \
    > config_sample.html

Collapse all, Expand all, Run layout それぞれボタンを押すとリソースを縮小、拡大、異動させることができます。

方法5. Inframap

該当リポジトリはこちらです。
inframap

5-1. インストール

cli
go install github.com/cycloidio/inframap@v0.6.7

5-2. 使用方法

cli
inframap generate terraform.tfstate --raw | dot -Tpng > inframapraw.png

場合によって画像が表示されなかった時、以下のコマンドを使用します。

cli
inframap generate \
> terraform.tfstate --raw | \
> dot -Tpng > inframap_sample.png

最後に

Terraformのコードをグラフとして可視化する方法はいくつかあります。最も基本的な方法は terraform graph コマンドを使用することですが、目的に応じて紹介した上記のツールを使うこともできます。よかったら、試してみてください。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?