Terraform
https://www.datocms-assets.com/2885/1620155113-brandhcterraformprimaryattributedcolor.svg
Terraform by HashiCorp
Terraform is an infrastructure as code (IaC) tool that allows you to build, change, and version infrastructure safely and efficiently. This includes both low-level components like compute instances, storage, and networking, as well as high-level components like DNS entries and SaaS features.
Install
Homebrew
asdf(おすすめ)
asdf-community/asdf-hashicorp: HashiCorp plugin for the asdf version manager
環境変数(ASDF_HASHICORP_)によるインストールオプションがある。
ARCH を指定できる。
code: (bash)
ASDF_HASHICORP_OVERWRITE_ARCH_TERRAFORM=amd64 asdf install terraform latest
ASDF_HASHICORP_OVERWRITE_ARCH_TERRAFORM=amd64 asdf global terraform latest
Tips
depends_on
依存関係を制御できる
The depends_on Meta-Argument - Configuration Language - Terraform by HashiCorp
file("credentials.json")が使用できないため、コマンド実行時に var を渡す
Allow terraform backend arguments to use functions and variables · Issue #22088 · hashicorp/terraform
.terraformignore
無視するファイル・ディレクトリを記載する
Version Constraints - Configuration Language | Terraform | HashiCorp Developer
=, ~> だけで良さそう
変数
sensitive
機密情報などに利用して、コマンド実行出力に表示されないようにする
code: (variables.tf)
variable "db_username" {
description = "Database administrator username"
type = string
sensitive = true
}
variable "db_password" {
description = "Database administrator password"
type = string
sensitive = true
}
外部から値を取得する
hashicorp/vault | Terraform Registry
tfstate には平文で保存されるので、backend の取り扱いに注意
git diff したものを TARGET 変数に設定する
code: (bash)
TARGET=$(git diff | grep --color=auto '\+resource' | awk -F '"' '{print "-target="$2"."$4}' | tr '\n' ' ')
terraform plan $TARGET
Resources
terraform_remote_state
異なる tfstate ファイルから値を読み込む
Provisioners
Provisioners | Terraform | HashiCorp Developer
Samples
code: (bash)
# 追加されたリソースを表示する
set TARGET (git diff | grep '+resource' | awk -F '"' '{print $2"."$4}')
terraform plan -target=$TARGET
Modules
Terraform Registry
Style Guide
Style Guide - Configuration Language | Terraform | HashiCorp Developer
Repository
リポジトリの分け方
Mono Repo
コードの一元管理、共通化
影響範囲が大きい
Multi Repo
コードを独立して管理
リモートモジュールをダウンロードする時間
Memo
ループ処理
count
count = N で N 個の resource, module を作成する
count.index で現在の値を利用できる
for_each
for_each = set で集合の要素だけ resource, module を作成する
for と組み合わせ可能
each.key, each.value で現在の値を利用できる
Terraformでのloop処理の書き方(for, for_each, count)
Terraform Cloud
State ファイルのみ管理もできる
Configuration Language
Overview - Configuration Language | Terraform | HashiCorp Developer
Reference
Best Practice
Index - Terraform Recommended Practices | Terraform | HashiCorp Developer
Terraform を使用するためのベスト プラクティス  |  Google Cloud
Terraform Moduleとディレクトリ管理で開発・本番環境を分ける | zoo200's MemoMemo
【Terraform🧑🏻‍🚀】tfstateファイル分割パターンとディレクトリー構成設計 - 好きな技術を布教したい 😗
terraform非対応リソースをlocal-execで管理する | A4 tech note
『Terraform と gcloud CLI を使用した完璧な Google Cloud インフラストラクチャの構築』は本当に完璧なのかやってみた - commmune Engineer Blog