セキュリティグループルールをオブジェクト変数として定義する

list(object({...}))を使用して型付きフィールドを持つ柔軟なセキュリティグループのイングレスおよびエグレスルールを定義するTerraform変数を作成します。

Networking

詳細な説明

オブジェクト変数としてのセキュリティグループルール

セキュリティグループルールはTerraform変数で複雑なオブジェクト型を使用する代表的な例です。ルールをリソースにハードコードする代わりに、変数として定義することでモジュールをプロジェクト間で再利用できます。

変数定義

variable "ingress_rules" {
  type = list(object({
    description = string
    from_port   = number
    to_port     = number
    protocol    = string
    cidr_blocks = list(string)
  }))
  description = "List of ingress rules for the security group"
  default = [
    {
      description = "HTTPS from anywhere"
      from_port   = 443
      to_port     = 443
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  ]
}

オブジェクト型のメリット

  • 型安全性: Terraformは各ルールオブジェクトに必要なすべてのフィールドがあることを検証
  • 自己文書化: 型定義が期待されるフィールドを正確に示す
  • IDEサポート: 型対応エディタがフィールド名を自動補完可能
  • エラー防止: 欠落または誤入力されたフィールドがplan時に検出される

環境別ルール

# dev.tfvars — 開発用のオープンアクセス
ingress_rules = [
  { description = "All from VPC", from_port = 0, to_port = 0, protocol = "-1", cidr_blocks = ["10.0.0.0/16"] }
]

# prod.tfvars — 制限されたアクセス
ingress_rules = [
  { description = "HTTPS only", from_port = 443, to_port = 443, protocol = "tcp", cidr_blocks = ["0.0.0.0/0"] }
]

ユースケース

異なる環境やアプリケーションが異なるファイアウォールルールを必要とする再利用可能なセキュリティグループモジュール。

試してみる — Terraform Variable Generator

フルツールを開く