概要
CDKでALB with Fargateを作るとSecurityGroupがフル開放されちゃいます
開発環境だったり、内部のサービスであれば、セキュリティを考えてIPを絞りたいと思うのですが、CDKだと追加は簡単だけど削除が難しかったので、その方法の共有です
手順
フルオープンSG作成
まずは変更対象のSecurityGroupを作成します
alb_sg=ec2.SecurityGroup(self, "alb-sg",
vpc=ivpc,
description="alb sg"
)
次にそのSecurityGroupを利用したALBを作成します
ecs_alb=elasticloadbalancingv2.ApplicationLoadBalancer(self, "alb",
security_group=alb_sg,
vpc=ivpc,
internet_facing=True,
load_balancer_name="ecs-alb"
)
そしてecs_patternsを使ってFargateServiceを作ります
fargate_service = ecs_patterns.ApplicationLoadBalancedFargateService(self, "service",
cluster=cluster,
task_definition=task,
load_balancer=ecs_alb,
cloud_map_options = ecs.CloudMapOptions(
name = 'hoge'
)
)
実行すると下記のように80ポートがフルオープンしたSecurityGroupが作成されることが分かります
(SecurityGroupの部分のみ抜き出してます)
$ cdk diff ecs
Stack ecs
Security Group Changes
┌───┬───────────────────────────────────────────────────────┬─────┬──────────┬────────────────────────────────┐
│ │ Group │ Dir │ Protocol │ Peer │
├───┼───────────────────────────────────────────────────────┼─────┼──────────┼────────────────────────────────┤
│ + │ ${prod-alb-sg.GroupId} │ In │ TCP 80 │ Everyone (IPv4) │
└───┴───────────────────────────────────────────────────────┴─────┴──────────┴────────────────────────────────┘
Resources
[~] AWS::EC2::SecurityGroup prod-alb-sg prodmonitoralbsg0D94D960
└─ [+] SecurityGroupIngress
└─ [{"CidrIp":"0.0.0.0/0","Description":"Allow from anyone on port 80","FromPort":80,"IpProtocol":"tcp","ToPort":80}]
SGの上書き
node.default_child.add_override
で上書きできるので、キーを指定して上書きします
下記2個を指定していて、フル開放されている1つしかルールが追加されてないので0番目を指定してます
- Properties.SecurityGroupIngress.0.CidrIp
- Properties.SecurityGroupIngress.0.Description
alb_sg.node.default_child.add_override(
"Properties.SecurityGroupIngress.0.CidrIp",
"1.1.1.1/32"
)
alb_sg.node.default_child.add_override(
"Properties.SecurityGroupIngress.0.Description",
"Google"
)
実行すると、デフォルトのTCP80 allow Everyoneが消えて指定したIPに変わります
$ SYSTEM_ENV=prod cdk diff ecs
Stack ecs
Security Group Changes
┌───┬────────────────────────────────┬─────┬──────────┬─────────────────┐
│ │ Group │ Dir │ Protocol │ Peer │
├───┼────────────────────────────────┼─────┼──────────┼─────────────────┤
│ - │ ${prod-alb-sg.GroupId} │ In │ TCP 80 │ Everyone (IPv4) │
├───┼────────────────────────────────┼─────┼──────────┼─────────────────┤
│ + │ ${prod-alb-sg.GroupId} │ In │ TCP 80 │ 1.1.1.1/32 │
└───┴────────────────────────────────┴─────┴──────────┴─────────────────┘
(NOTE: There may be security-related changes not in this list. See https://github.com/aws/aws-cdk/issues/1299)
Resources
[~] AWS::EC2::SecurityGroup prod-alb-sg prodmonitoralbsg0D94D960
└─ [~] SecurityGroupIngress
└─ @@ -1,7 +1,7 @@
[ ] [
[ ] {
[-] "CidrIp": "0.0.0.0/0",
[-] "Description": "Allow from anyone on port 80",
[+] "CidrIp": "1.1.1.1/32",
[+] "Description": "Google",
[ ] "FromPort": 80,
[ ] "IpProtocol": "tcp",
[ ] "ToPort": 80
以上がCDKからALBデフォルトSGのいじり方でした