
AWS Security Hub を導入して AWS Foundational Security Best Practices (FSBP) などを有効化すると VPC default security groups should not allow inbound or outbound traffic という警告が検出されることがある🚨
[EC2.2] VPC default security groups should not allow inbound or outbound traffic This control checks whether the default security group of a VPC allows inbound or outbound traffic. The control fails if the security group allows inbound or outbound traffic.
簡単に言うと Amazon VPC を作るときに自動的に作られる default セキュリティグループのルール(インバウンド・アウトバウンド)を削除しておくことで意図しないトラフィックを防げるよー💡ということ.また default セキュリティグループ自体は削除できない仕様になっているところもポイントと言える.
Terraform で default セキュリティグループのルールを削除する
コンソールからポチポチと default セキュリティグループのルールを削除することもできるけど,せっかく Terraform で構築した Amazon VPC なら default セキュリティグループも Terraform で管理したいな〜ということで aws_default_security_group リソースが使える👏
ドキュメントに create ではなく adopt という注意点も書いてある通り,aws_default_security_group リソースは少し特殊で,通常の Terraform リソースのように追加するのではなく「もともとある設定を上書きする」ような挙動になる(terraform import ともまた違う).
とは言え実装自体は簡単で,以下のように実装すれば,新しく追加する Amazon VPC の default セキュリティグループのルール(インバウンド・アウトバウンド)を削除することができる❗️
resource "aws_vpc" "sandbox" { cidr_block = "10.0.0.0/16" } resource "aws_default_security_group" "sandbox" { vpc_id = aws_vpc.sandbox.id }
Terraform で default VPC の default セキュリティグループのルールを削除する
もし default VPC を残している場合は default VPC の default セキュリティグループの考慮も必要になる.
Terraform で default VPC 自体を削除する場合は aws_default_vpc リソースに紐付けてから force_destroy = true を指定すれば削除できる.
resource "aws_default_vpc" "default" { force_destroy = true }
しかし default VPC は残しつつも default セキュリティグループのルールは削除したいという場面もあると思う.そういうときは aws_vpc データソースに default = true を指定して default VPC を参照しつつ,同じように aws_default_security_group リソースで設定を上書きすれば OK👌
data "aws_vpc" "default" { default = true } resource "aws_default_security_group" "default" { vpc_id = data.aws_vpc.default.id }