-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSecurityGroups.py
86 lines (77 loc) · 3.1 KB
/
SecurityGroups.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
This module contains the SecurityGroups NestedStack class.
"""
from aws_cdk import (
NestedStack,
Tags,
aws_ec2 as ec2,
)
from constructs import Construct
### Nested Stack info:
# https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.NestedStack.html
class SecurityGroups(NestedStack):
"""
This sets up the Security Groups for everything. Broke it
out to avoid circular imports.
"""
def __init__(
self,
scope: Construct,
leaf_construct_id: str,
vpc: ec2.Vpc,
container_id: str,
container_ports_config: list,
**kwargs,
) -> None:
super().__init__(scope, "SecurityGroupsNestedStack", **kwargs)
## Security Group for Container's traffic:
# https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SecurityGroup.html
self.sg_container_traffic = ec2.SecurityGroup(
self,
"SgContainerTraffic",
vpc=vpc,
description=f"({container_id}): Traffic for the Container",
# Impossible to know container will need/want:
allow_all_outbound=True,
)
# Create a name of `<StackName>/sg-container-traffic` to find it easier:
Tags.of(self.sg_container_traffic).add("Name", f"{leaf_construct_id}/sg-container-traffic")
## Allow SSH traffic:
self.sg_container_traffic.connections.allow_from(
ec2.Peer.any_ipv4(),
# Same as TCP 22:
ec2.Port.SSH,
description="Allow SSH traffic IN",
)
## Security Group for EFS instance's traffic:
# https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_ec2.SecurityGroup.html
self.sg_efs_traffic = ec2.SecurityGroup(
self,
"SgEfsTraffic",
vpc=vpc,
description=f"({container_id}): Traffic for the EFS instance",
# Lock down to JUST talk with the container and host:
allow_all_outbound=False,
)
# Create a name of `<StackName>/sg-efs-traffic` to find it easier:
Tags.of(self.sg_efs_traffic).add("Name", f"{leaf_construct_id}/sg-efs-traffic")
## Allow EFS to receive traffic from the container:
# (sg's are stateful, so it can reply too)
self.sg_efs_traffic.connections.allow_from(
self.sg_container_traffic,
port_range=ec2.Port.tcp(2049),
description="Allow EFS traffic IN - from container",
)
# Loop over each port and figure out what it wants:
for port_mapping in container_ports_config:
## Get the string "TCP" or "UDP":
# Starts from 'Protocol.TCP'
protocol = str(port_mapping.protocol).split(".")[1]
## Get the port. Both 'host_port' and 'container_port'
# are the same.
port = port_mapping.host_port
self.sg_container_traffic.connections.allow_from(
ec2.Peer.any_ipv4(),
getattr(ec2.Port, protocol.lower())(port),
description=f"Game port: allow {protocol.lower()} traffic IN from {port}",
)