-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathvpc.cfndsl.rb
More file actions
377 lines (325 loc) · 10.8 KB
/
vpc.cfndsl.rb
File metadata and controls
377 lines (325 loc) · 10.8 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
CloudFormation do
# Render AZ conditions
maximum_availability_zones = external_parameters.fetch(:maximum_availability_zones, 5)
az_conditions(maximum_availability_zones)
max_nat_conditions(maximum_availability_zones)
# Render NAT Gateway and EIP Conditions
Condition(:NatEnabled, FnEquals(Ref(:NatEnabled), 'true'))
maximum_availability_zones.times do |x|
Condition("Nat#{x}EIPRequired", FnEquals(Ref("Nat#{x}EIPAllocationId"), 'dynamic'))
Condition("SingleNatRoute#{x}Create", FnAnd([
Condition("RoutedBySingleNat#{x}"),
Condition(:NatEnabled)
]))
Condition("NatRoute#{x}Create", FnAnd([
Condition("RoutedByNat#{x}"),
Condition(:NatEnabled)
]))
Condition("NatGateway#{x}Create", FnAnd([
Condition("NatGateway#{x}Exist"),
Condition(:NatEnabled)
]))
Condition("NatIPAddress#{x}Required", FnAnd([
Condition("NatGateway#{x}Exist"),
Condition("Nat#{x}EIPRequired"),
Condition(:NatEnabled)
]))
end
tags = []
tags << { Key: 'Environment', Value: Ref(:EnvironmentName) }
tags << { Key: 'EnvironmentType', Value: Ref(:EnvironmentType) }
extra_tags = external_parameters.fetch(:extra_tags, {})
extra_tags.each { |key,value| tags << { Key: key, Value: value } }
# VPC Itself
vpc_tags = []
vpc_tags += tags
vpc_tags << { Key: 'Name', Value: FnSub('${EnvironmentName}-vpc') }
VPC('VPC') do
CidrBlock(
FnJoin('',
[Ref('NetworkPrefix'),
'.',
Ref('StackOctet'),
'.0.0/',
Ref('StackMask')]
)
)
EnableDnsSupport true
EnableDnsHostnames true
Tags vpc_tags
end
unless external_parameters[:manage_ns_records]
Route53_HostedZone('HostedZone') do
Name FnSub(dns_format)
HostedZoneConfig ({
Comment: FnSub("Hosted Zone for ${EnvironmentName}")
})
HostedZoneTags tags
end
end
EC2_DHCPOptions('DHCPOptionSet') do
DomainName FnSub(dns_format)
DomainNameServers ['AmazonProvidedDNS']
end
EC2_VPCDHCPOptionsAssociation('DHCPOptionsAssociation') do
VpcId Ref('VPC')
DhcpOptionsId Ref('DHCPOptionSet')
end
EC2_InternetGateway('InternetGateway')
EC2_VPCGatewayAttachment('AttachGateway') do
VpcId Ref('VPC')
InternetGatewayId Ref('InternetGateway')
end
EC2_NetworkAcl('PublicNetworkAcl') do
VpcId Ref('VPC')
end
external_parameters[:public_acl_rules].each do |type, entries|
entries.each do |entry|
if entry.key? 'ips'
increment = 0
entry['ips'].each do |block|
lookup_ips(ip_blocks, block).each_with_index do |cidr|
entry_ipblock = entry.clone
entry_ipblock['number'] = entry['number'].to_i + increment
nacl_entry(cidr, entry_ipblock, type, Ref('PublicNetworkAcl'))
increment = increment + 1
end
end
else
cidr_block = entry['cidr'] || '0.0.0.0/0'
nacl_entry(cidr_block, entry, type, Ref('PublicNetworkAcl'))
end
end
end
# Public subnets route table
EC2_RouteTable('RouteTablePublic') do
VpcId Ref('VPC')
Tags [{ Key: 'Name', Value: FnJoin("", [Ref('EnvironmentName'), "-public"]) }]
end
# Public subnet internet route
EC2_Route('PublicRouteOutToInternet') do
DependsOn ['AttachGateway']
RouteTableId Ref("RouteTablePublic")
DestinationCidrBlock '0.0.0.0/0'
GatewayId Ref("InternetGateway")
end
maximum_availability_zones.times do |az|
# Private subnet route tables
EC2_RouteTable("RouteTablePrivate#{az}") do
Condition "Az#{az}"
VpcId Ref('VPC')
Tags [{ Key: 'Name', Value: FnJoin("", [Ref('EnvironmentName'), "-private#{az}"]) }]
end
# Nat Gateway IPs and Nat Gateways
EC2_EIP("NatIPAddress#{az}") do
DependsOn ["AttachGateway"]
Condition("NatIPAddress#{az}Required")
Domain 'vpc'
end
EC2_NatGateway("NatGateway#{az}") do
Condition "NatGateway#{az}Create"
# If EIP is passed manually as param, use that EIP, otherwise use one from
# generated by CloudFormation
AllocationId FnIf("Nat#{az}EIPRequired",
FnGetAtt("NatIPAddress#{az}", 'AllocationId'),
Ref("Nat#{az}EIPAllocationId")
)
SubnetId Ref("SubnetPublic#{az}")
end
# Private subnet internet route through NAT Gateway
EC2_Route("RouteOutToInternet#{az}") do
Condition("NatRoute#{az}Create")
DependsOn ["NatGateway#{az}"]
RouteTableId Ref("RouteTablePrivate#{az}")
DestinationCidrBlock '0.0.0.0/0'
NatGatewayId Ref("NatGateway#{az}")
end
EC2_Route("RouteOutToInternet#{az}Nat0") do
Condition "SingleNatRoute#{az}Create"
DependsOn ["NatGateway0"]
RouteTableId Ref("RouteTablePrivate#{az}")
DestinationCidrBlock '0.0.0.0/0'
NatGatewayId Ref("NatGateway0")
end
end
# Create defined subnets
external_parameters[:subnets].each do |name, config|
subnetRefs = []
subnet_tags = []
subnet_tags += tags
config['tags'].each { |key,value| subnet_tags << { Key: FnSub(key.to_s), Value: FnSub(value.to_s) } } if config.has_key?('tags')
newSubnets = az_create_subnets(
config['allocation'],
config['name'],
config['type'],
'VPC',
maximum_availability_zones,
subnet_tags
)
newSubnets.each_with_index do |subnet_name,az|
subnet_name_az = "Subnet#{subnet_name}"
Output("Subnet#{subnet_name}") do
Value(FnIf("Az#{az}", Ref(subnet_name_az), ''))
end
subnetRefs << Ref(subnet_name_az)
end
subnet_list = az_conditional_resources_internal("Subnet#{config['name']}",maximum_availability_zones)
Output("#{config['name']}Subnets") {
Value(FnJoin(',', subnet_list))
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-#{config['name']}Subnets")
}
end
route_tables = az_conditional_resources_internal('RouteTablePrivate', maximum_availability_zones)
EC2_VPCEndpoint('VPCEndpoint') do
VpcId Ref('VPC')
PolicyDocument({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Principal: "*",
Action: ["s3:*"],
Resource: ["arn:aws:s3:::*"]
}]
})
ServiceName FnJoin("", ["com.amazonaws.", Ref("AWS::Region"), ".s3"])
RouteTableIds route_tables
end
securityGroups = external_parameters[:securityGroups]
if securityGroups.key?('ops')
EC2_SecurityGroup('SecurityGroupOps') do
VpcId Ref('VPC')
GroupDescription 'Ops External Access'
SecurityGroupIngress sg_create_rules(securityGroups['ops'], ip_blocks)
Metadata({
cfn_nag: {
rules_to_suppress: [
{ id: 'F1000', reason: 'plan is to remove these security groups or make them conditional' }
]
}
})
end
end
if securityGroups.key?('dev')
EC2_SecurityGroup('SecurityGroupDev') do
VpcId Ref('VPC')
GroupDescription 'Dev Team Access'
SecurityGroupIngress sg_create_rules(securityGroups['dev'], ip_blocks)
Metadata({
cfn_nag: {
rules_to_suppress: [
{ id: 'F1000', reason: 'plan is to remove these security groups or make them conditional' }
]
}
})
end
end
if securityGroups.key?('backplane')
EC2_SecurityGroup('SecurityGroupBackplane') do
VpcId Ref('VPC')
GroupDescription 'Backplane SG'
SecurityGroupIngress sg_create_rules(securityGroups['backplane'], ip_blocks)
Metadata({
cfn_nag: {
rules_to_suppress: [
{ id: 'F1000', reason: 'plan is to remove these security groups or make them conditional' }
]
}
})
end
end
if external_parameters[:enable_transit_vpc]
VPNGateway('VGW') do
Type 'ipsec.1'
if external_parameters[:vgw_asn]
AmazonSideAsn external_parameters[:vgw_asn]
end
Tags [
{ Key: 'Name', Value: FnJoin("", [Ref('EnvironmentName'), "-VGW"]) },
{ Key: 'transitvpc:spoke', Value: Ref('EnableTransitVPC') }
]
end
VPCGatewayAttachment('AttachVGWToVPC') do
VpcId Ref('VPC')
VpnGatewayId Ref('VGW')
end
VPNGatewayRoutePropagation('PropagateRoute') do
DependsOn ['AttachVGWToVPC']
RouteTableIds route_tables
VpnGatewayId Ref('VGW')
end
end
# Outputs
Output("VPCId") {
Value(Ref('VPC'))
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-VPCId")
}
Output("VPCCidr") {
Value(FnGetAtt('VPC', 'CidrBlock'))
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-VPCCidr")
}
Output("SecurityGroupOps") {
Value(Ref('SecurityGroupOps'))
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-SecurityGroupOps")
}
Output("SecurityGroupDev") {
Value(Ref('SecurityGroupDev'))
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-SecurityGroupDev")
}
Output("SecurityGroupBackplane") {
Value(Ref('SecurityGroupBackplane'))
Export FnSub("${EnvironmentName}-#{external_parameters[:component_name]}-SecurityGroupBackplane")
}
nat_ip_list = nat_gateway_ips_list_internal(maximum_availability_zones)
Output('NatGatewayIps') {
Condition(:NatEnabled)
Value(FnJoin(',', nat_ip_list))
}
flowlogs = external_parameters.fetch(:flowlogs, {})
unless flowlogs.empty?
log_retention = (flowlogs.is_a?(Hash) && flowlogs.has_key?('log_retention')) ? flowlogs['log_retention'] : 7
Resource('FlowLogsLogGroup') {
Type 'AWS::Logs::LogGroup'
Property('LogGroupName', Ref('AWS::StackName'))
Property('RetentionInDays', "#{log_retention}")
}
IAM_Role("PutVPCFlowLogsRole") do
AssumeRolePolicyDocument ({
Statement: [
{
Effect: 'Allow',
Principal: {
Service: 'vpc-flow-logs.amazonaws.com'
},
Action: [ 'sts:AssumeRole' ]
}
]
})
Path '/'
Policies ([
PolicyName: 'PutVPCFlowLogsRole',
PolicyDocument: {
Statement: [
{
Effect: 'Allow',
Action: [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams"
],
Resource: '*'
}
]
}
])
end
EC2_FlowLog("VPCFlowLogs") do
DeliverLogsPermissionArn FnGetAtt('PutVPCFlowLogsRole', 'Arn')
LogGroupName Ref('FlowLogsLogGroup')
ResourceId Ref('VPC')
ResourceType 'VPC'
TrafficType (flowlogs.is_a?(Hash) && flowlogs.has_key?('traffic_type')) ? flowlogs['traffic_type'] : 'ALL'
end
end
end