/
vpc.py
300 lines (245 loc) · 10.4 KB
/
vpc.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
from troposphere import (
Parameter,
Ref,
Output,
Tags,
Join,
ec2
)
from utils.cfn import (
get_availability_zones,
get_recent_ami,
get_subnet_cidr_block
)
from utils.constants import (
ALLOW_ALL_CIDR,
EC2_INSTANCE_TYPES,
HTTP,
HTTPS,
VPC_CIDR
)
from majorkirby import StackNode, MKUnresolvableInputError
cidr_generator = get_subnet_cidr_block()
class VPC(StackNode):
INPUTS = {
'Tags': ['global:Tags'],
'Region': ['global:Region'],
'StackType': ['global:StackType'],
'KeyName': ['global:KeyName'],
'AvailabilityZones': ['global:AvailabilityZones'],
'NATInstanceType': ['global:NATInstanceType'],
'NATInstanceAMI': ['global:NATInstanceAMI'],
}
DEFAULTS = {
'Tags': {},
'Region': 'us-east-1',
'StackType': 'Staging',
'KeyName': 'mmw-stg',
'AvailabilityZones': 'us-east-1b,us-east-1d',
'NATInstanceType': 't2.micro',
}
ATTRIBUTES = {'StackType': 'StackType'}
PUBLIC_SUBNETS = []
PRIVATE_SUBNETS = []
_NAT_SECURITY_GROUP_CACHE = None
def set_up_stack(self):
super(VPC, self).set_up_stack()
tags = self.get_input('Tags').copy()
tags.update({'StackType': 'VPC'})
self.default_tags = tags
self.region = self.get_input('Region')
self.availability_zones = get_availability_zones(self.aws_profile)
self.add_description('VPC stack for MMW')
# Parameters
self.keyname = self.add_parameter(Parameter(
'KeyName', Type='String',
Description='Name of an existing EC2 key pair'
), 'KeyName')
self.nat_instance_type = self.add_parameter(Parameter(
'NATInstanceType', Type='String', Default='t2.micro',
Description='NAT EC2 instance type',
AllowedValues=EC2_INSTANCE_TYPES,
ConstraintDescription='must be a valid EC2 instance type.'
), 'NATInstanceType')
self.nat_instance_ami = self.add_parameter(Parameter(
'NATInstanceAMI', Type='String', Default=self.get_recent_nat_ami(),
Description='NAT EC2 Instance AMI'
), 'NATInstanceAMI')
public_route_table = self.create_vpc()
self.add_output(Output('AvailabilityZones',
Value=','.join(self.default_azs)))
self.add_output(Output('PrivateSubnets',
Value=Join(',', map(Ref, self.default_private_subnets)))) # NOQA
self.add_output(Output('PublicSubnets',
Value=Join(',', map(Ref, self.default_public_subnets)))) # NOQA
self.add_output(Output('RouteTableId', Value=Ref(public_route_table)))
def get_recent_nat_ami(self):
try:
nat_ami_id = self.get_input('NATInstanceAMI')
except MKUnresolvableInputError:
nat_ami_id = get_recent_ami(self.aws_profile, '*ami-vpc-nat-hvm*',
owner='amazon')
return nat_ami_id
def create_vpc(self):
vpc_name = 'MMWVPC'
self.vpc = self.create_resource(ec2.VPC(
vpc_name,
CidrBlock=VPC_CIDR, EnableDnsSupport=True,
EnableDnsHostnames=True, Tags=self.get_tags(Name=vpc_name)
), output='VpcId')
public_route_table = self.create_routing_resources()
self.create_subnets(public_route_table)
return public_route_table
def create_routing_resources(self):
gateway = self.create_resource(
ec2.InternetGateway(
'InternetGateway',
Tags=self.get_tags()
)
)
gateway_attachment = self.create_resource(
ec2.VPCGatewayAttachment(
'VPCGatewayAttachment',
VpcId=Ref(self.vpc),
InternetGatewayId=Ref(gateway)
)
)
public_route_table = self.create_resource(
ec2.RouteTable(
'PublicRouteTable',
VpcId=Ref(self.vpc))
)
self.create_resource(
ec2.Route(
'PublicRoute',
RouteTableId=Ref(public_route_table),
DestinationCidrBlock=ALLOW_ALL_CIDR,
DependsOn=gateway_attachment.title,
GatewayId=Ref(gateway)
)
)
return public_route_table
def create_subnets(self, public_route_table):
self.default_azs = []
self.default_private_subnets = []
self.default_public_subnets = []
for num, availability_zone in enumerate(self.availability_zones):
public_subnet_name = '{}PublicSubnet'.format(availability_zone.cfn_name) # NOQA
public_subnet = self.create_resource(ec2.Subnet(
public_subnet_name,
VpcId=Ref(self.vpc),
CidrBlock=cidr_generator.next(),
AvailabilityZone=availability_zone.name,
Tags=self.get_tags(Name=public_subnet_name)
))
self.create_resource(ec2.SubnetRouteTableAssociation(
'{}PublicRouteTableAssociation'.format(public_subnet.title),
SubnetId=Ref(public_subnet),
RouteTableId=Ref(public_route_table)
))
private_subnet_name = '{}PrivateSubnet'.format(availability_zone.cfn_name) # NOQA
private_subnet = self.create_resource(ec2.Subnet(
private_subnet_name,
VpcId=Ref(self.vpc),
CidrBlock=cidr_generator.next(),
AvailabilityZone=availability_zone.name,
Tags=self.get_tags(Name=private_subnet_name)
))
private_route_table_name = '{}PrivateRouteTable'.format(availability_zone.cfn_name) # NOQA
private_route_table = self.create_resource(ec2.RouteTable(
private_route_table_name,
VpcId=Ref(self.vpc),
Tags=self.get_tags(Name=private_route_table_name)
))
self.create_resource(ec2.SubnetRouteTableAssociation(
'{}PrivateSubnetRouteTableAssociation'.format(private_subnet.title), # NOQA
SubnetId=Ref(private_subnet),
RouteTableId=Ref(private_route_table)
))
self.PUBLIC_SUBNETS.append(public_subnet)
self.PRIVATE_SUBNETS.append(private_subnet)
if availability_zone.name in self.get_input('AvailabilityZones').split(','): # NOQA
self.create_nat(availability_zone, public_subnet,
private_route_table)
self.default_azs.append(availability_zone.name)
self.default_private_subnets.append(private_subnet)
self.default_public_subnets.append(public_subnet)
def create_nat(self, availability_zone, public_subnet, private_route_table): # NOQA
nat_device_name = '{}NATDevice'.format(availability_zone.cfn_name)
nat_device = self.create_resource(ec2.Instance(
nat_device_name,
InstanceType=Ref(self.nat_instance_type),
KeyName=Ref(self.keyname),
SourceDestCheck=False,
ImageId=Ref(self.nat_instance_ami),
NetworkInterfaces=[
ec2.NetworkInterfaceProperty(
Description='ENI for NATDevice',
GroupSet=[Ref(self.nat_security_group)],
SubnetId=Ref(public_subnet),
AssociatePublicIpAddress=True,
DeviceIndex=0,
DeleteOnTermination=True,
)
],
Tags=self.get_tags(Name=nat_device_name)
))
self.create_resource(ec2.Route(
'{}PrivateRoute'.format(availability_zone.cfn_name),
RouteTableId=Ref(private_route_table),
DestinationCidrBlock=ALLOW_ALL_CIDR,
InstanceId=Ref(nat_device))
)
@property
def nat_security_group(self):
if self._NAT_SECURITY_GROUP_CACHE:
return self._NAT_SECURITY_GROUP_CACHE
else:
nat_security_group_name = 'sgNAT'
self._NAT_SECURITY_GROUP_CACHE = self.create_resource(
ec2.SecurityGroup(nat_security_group_name,
GroupDescription='Enables access to the NAT '
'devices',
VpcId=Ref(self.vpc),
SecurityGroupIngress=[
ec2.SecurityGroupRule(
IpProtocol='tcp', CidrIp=VPC_CIDR,
FromPort=p, ToPort=p
)
for p in [HTTP, HTTPS]
],
SecurityGroupEgress=[
ec2.SecurityGroupRule(
IpProtocol='tcp',
CidrIp=ALLOW_ALL_CIDR,
FromPort=port, ToPort=port
) for port in [HTTP, HTTPS]
],
Tags=self.get_tags(Name=nat_security_group_name)), # NOQA
'NATSecurityGroup'
)
return self._NAT_SECURITY_GROUP_CACHE
def create_resource(self, resource, output=None):
"""Helper method to attach resource to template and return it
This helper method is used when adding _any_ CloudFormation resource
to the template. It abstracts out the creation of the resource, adding
it to the template, and optionally adding it to the outputs as well
Args:
resource: Troposphere resource to create
output: Name of output to return this value as
"""
resource = self.add_resource(resource)
if output:
cloudformation_output = Output(
output,
Value=Ref(resource)
)
self.add_output(cloudformation_output)
return resource
def get_tags(self, **kwargs):
"""Helper method to return Troposphere tags + default tags
Args:
**kwargs: arbitrary keyword arguments to be used as tags
"""
kwargs.update(self.default_tags)
return Tags(**kwargs)