Terraform
Page content
Terraform
クラウドプロバイダ上のリソースを管理する Infrastructure as Code なツールとして有名な Terraform (by HashiCorp 社) について試した。
![]()
特徴
- 管理できるリソース
- AWS で言えば EC2 はもちろん、 VPC のネットワーク設定 (SDN 的な要素と言っている)
インストール (2022/12/09)
https://github.com/hashicorp/terraform/releases を見ればわかるけど、結構頻繁にバージョンが上がる。
そこで https://dev.classmethod.jp/articles/beginner-terraform-install-mac/ にあるようにまず tfenv をインストールして、 Terraform 自体のバージョン管理をするのが良さそう。
その手順でやってみる
$ brew install tfenv
$ tfenv --version
tfenv 3.0.0
$ tfenv list-remote
1.4.0-alpha20221207
1.4.0-alpha20221109
1.3.6
1.3.5
1.3.4
...
$ tfenv install 1.3.6
Installing Terraform v1.3.6
Downloading release tarball from https://releases.hashicorp.com/terraform/1.3.6/terraform_1.3.6_darwin_arm64.zip
...
Installation of terraform v1.3.6 successful. To make this your default version, run 'tfenv use 1.3.6'
$ tfenv list
1.3.6
No default set. Set with 'tfenv use <version>'
$ tfenv use 1.3.6
Switching default version to v1.3.6
Default version (when not overridden by .terraform-version or TFENV_TERRAFORM_VERSION) is now: 1.3.6
$ tfenv list
* 1.3.6 (set by /opt/homebrew/Cellar/tfenv/3.0.0/version)
$ terraform version
Terraform v1.3.6
on darwin_arm64
- Main commands:
init Prepare your working directory for other commands validate Check whether the configuration is valid plan Show changes required by the current configuration apply Create or update infrastructure destroy Destroy previously-created infrastructure
tutorial というかお試しと言うか
参考にやってみる: 10分で理解するTerraform
- サイクル
- 新規
.tfファイルを作って,terraform init.tfファイルをちゃんと定義しきったらterraform planで適用したら何が起きるかの確認- 実際の適用は
terraform apply - 最新の状態の出力は
terraform showで見る
- 更新・運用
- 定義を変更してみる
terraform planで適用予定の内容と現状との差分を確認terraform applyで変更を適用terraform showで確認
- 廃止
terraform destroyで実際に削除terraform showで管理しているリソースがなにもないことを確認
- 新規
Serverless Framework をカバーできるか?
否。
- Lambda を管理するのが辛いらしい。 LambdaをTerraformで管理してた辛みをApexに乗り換えて解決した〜Datadog Logsの例を添えて〜
- ローカルでのテストもなさそう
terraform graph コマンド - graphviz で可視化
公式ガイドはこちら
# 事前に graphviz をインストールしておく
brew install graphviz
# plan のグラフを出力
terraform graph -type=plan | dot -Tpng > graph.png
こんな感じの図になる

terraform-graph-beautifier で更にきれいな可視化
https://github.com/pcasteran/terraform-graph-beautifier の通り。
docker コンテナが動く状態なら、以下のようにコンテナに terraform graph の出力を渡して、html 形式で出力できる。
terraform graph |\
docker run --rm -i --name terraform-graph-beautifier \
ghcr.io/pcasteran/terraform-graph-beautifier:latest-darwin \
--output-type=cyto-html > config1.html
イメージこんな感じで、 collapse/expand できるのが便利。
