terraform で workspace 使って環境ごとの変数の読み込みをする

terraform の workspace 使っていて「本番と staging で変数名変えたいときにはどうするんだろうなぁ?」って思って調べたんだけど、
ドキュメント探してもたどり着かず、結局以下の issue のようにした
Feature: Conditionally load tfvars/tf file based on Workspace · Issue #15966 · hashicorp/terraform · GitHub

以下のようなディレクトリ構造だとして、

.
├── main.tf
├── modules
└── workspaces
    ├── production
    │   └── tfenv.json
    └── staging
        └── tfenv.json

例えば staging の tfenv.json が以下のようになっているときに

{
  "db_host": "staging.example.com",
  "db_name": "staging"
}

main.tf に以下のように書いて解決。

locals {
  // デフォルト値があるやつはここに書いちゃう
  default_env = {
    db_name = "default_db"
  }
  tfvarsfile        = "workspaces/${terraform.workspace}/tfenv.json"
  tfvarsfilecontent = fileexists(local.tfvarsfile) ? file(local.tfvarsfile) : "{}"
  tfvars            = jsondecode(local.tfvarsfilecontent)
  tfenv             = merge(local.default_env, local.tfvars)
}

module "base" {
  tfenv                  = local.tfenv

  source = "./modules"
}