再利用可能モジュール間の相互参照を避ける
ルール
Avoid cross-referencing between reusable modules. Control references from the caller as much as possible
(再利用可能モジュール間の相互参照を避ける。参照は可能な限り呼び出し側で制御する)
解説
モジュール間の相互参照は取り回しを大きく損なうためできる限り避けます。
よく問題を起こすのがセキュリティグループルールで、呼び出し元と呼び出し先が別のモジュールでかつoutboundとinboundをきちんと指定するだけで相互参照になってしまいます。このようなケースではエッジモジュール(配線専用モジュール)を別に用意し、そのモジュール内でルールを設定します。カプセル化の観点からは好ましくないのですが、制約上いたしかたのない妥協と言えます。
サンプルコード
# main.tf (ルートモジュール)
module "networking" {
source = "./modules/networking"
vpc_cidr = var.vpc_cidr
}
module "database" {
source = "./modules/database"
# 呼び出し側で依存関係を明示的に制御
vpc_id = module.networking.vpc_id
subnet_ids = module.networking.private_subnet_ids
security_group_id = module.networking.db_security_group_id
}
# modules/database内で直接 module.networking を参照しない
参考リンク
Show Text to Share再利用可能モジュール間の相互参照を避ける https://www.tricrow.com/infrastructure/development-guidline/repository_structure.standard.module_ref.html

