This repository has been archived by the owner on Sep 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
keeping-secrets-vpc-20181108.yaml
570 lines (498 loc) · 16.9 KB
/
keeping-secrets-vpc-20181108.yaml
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Keeping Secrets VPC.yaml
#
# This CloudFormation template creates the core VPC infrastructure for
#
# AWS Security Services.
#
# The template builds the following resources:
#
# - an Amazon VPC
# - an internet gateway with a gateway attachment to the VPC
# - a route table
# - a default route
#
# It also exports:
#
# - the VPC
# - the route table
# - the session manager subnets
# - the secrets manager subnets (on which the database will go)
---
AWSTemplateFormatVersion: '2010-09-09'
Description: VPC for 2018 re:Invent Keeping Secrets chalk talk.
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
-
Label:
default: 'Core Parameters'
Parameters:
- VpcCidrOctet1
- VpcCidrOctet2
- NamePrefix
- ProjectTag
ParameterLabels:
VpcCidrOctet1:
default: 'Enter the value for the first octet of the VPC CIDR block:'
VpcCidrOctet2:
default: 'Enter the value for the second octet of the VPC CIDR block:'
NamePrefix:
default: 'Enter a prefix for the CloudFormation Name tag values:'
ProjectTag:
default: 'Enter the value for the Project tag:'
Parameters:
# VpcCidrOctet1 - First octet of VPC CIDR block
VpcCidrOctet1:
Type: Number
AllowedValues:
- 10
- 172
- 192
Default: 10
# VpcCidrOctet2 - Second octet of VPC CIDR block
VpcCidrOctet2:
Type: Number
MinValue: 1
MaxValue: 254
Default: 200
# NamePrefix - A prefix to apply to the Name tag of taggable resources.
# The Name tag will be set to the NamePrefix, a dash ("-"), and a suffix
# that varies based on the resource. You would typically accept the default.
NamePrefix:
Type: String
Default: 'keepingsecrets'
MinLength: 2
MaxLength: 15
AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
# ProjectTag - A value to apply to the Project tag of taggable resources. You
# would typically accept the default.
ProjectTag:
Type: String
Default: 'keepingsecrets'
MinLength: 2
MaxLength: 15
AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
Resources:
# Vpc - Our VPC
Vpc:
Type: AWS::EC2::VPC
Properties:
CidrBlock:
!Join
- ''
- - !Ref VpcCidrOctet1
- '.'
- !Ref VpcCidrOctet2
- '.0.0/16'
EnableDnsSupport: 'true'
EnableDnsHostnames: 'true'
Tags:
- Key: Name
Value: !Join [ '', [ Ref: NamePrefix, '-vpc' ]]
- Key: Project
Value: !Ref ProjectTag
# VpcIgw and VpcIgwAttachment - Set up the Internet gateway
# and the attachment.
VpcIgw:
Type: AWS::EC2::InternetGateway
Properties:
Tags:
- Key: Name
Value: !Join [ '', [ Ref: NamePrefix, '-igw' ]]
- Key: Project
Value: !Ref ProjectTag
VpcIgwAttachment:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
InternetGatewayId: !Ref VpcIgw
VpcId: !Ref Vpc
# PublicRouteTable - The public route table
PublicRouteTable:
Type: AWS::EC2::RouteTable
DependsOn: VpcIgwAttachment
Properties:
VpcId: !Ref Vpc
Tags:
- Key: Name
Value: !Join [ '', [ Ref: NamePrefix, '-rtb' ]]
- Key: Project
Value: !Ref ProjectTag
# DefaultPublicRoute - The default route to the public internet.
DefaultPublicRoute:
Type: AWS::EC2::Route
DependsOn: VpcIgwAttachment
Properties:
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref VpcIgw
RouteTableId: !Ref PublicRouteTable
# LambdaExecutionRole - Lambda excution role for our Lambda functions
#
# I am using the same Lambda execution role for all of the functions.
# In a production scenario, I would use separate Lambda roles tailored to
# each Lambda function to enforce the principle of least privilege.
LambdaExecutionRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: '/'
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- ec2:DescribeVpcEndpointServices
Resource: '*'
# VpcEndpointServiceAzsFunction
#
# This is the AWS Lambda function that supports a CloudFormation custom
# resource that is used to look up the available Availability Zones for
# a VPC interface endpoint service. VPC interface endpoints may only be
# offered in some, perhaps not all, AZs within a given region. This function
# can help you to design CloudFormation templates that choose subnets based
# on their ability to provide such endpoint interfaces.
#
# Resource properties (e.g. input "parameters") for the function:
#
# ServiceName - required - string - the name of the service. This should be
# something like 'com.amazonaws.us-east-1.secretsmanager'
#
# DesiredNumAzs - required - string - the minimum number of Availability Zones
# that must offer the service (usually '2' or '3'). This should be a whole
# number (i.e. a non-negative integer).
#
#
# Return values via GetAtt:
#
# NumAzs - string - the number of Availability Zones that offer the interface
# endpoint.
#
# Azs - string - a comma-separated list of the AZs.
#
# Errors:
#
# If there are any errors, the Lambda function returns a FAILED status which
# normally triggers a rollback in AWS CloudFormation. You can see the errors
# in the Amazon CloudWatch Logs.
#
# Notes:
#
# (1) Lambda function code inside of CloudFormation templates cannot exceed
# 4096 characters.
VpcEndpointServiceAzsFunction:
Type: AWS::Lambda::Function
Properties:
Description: 'Look up the AZs that are available for a VPC endpoint for a service'
Handler: index.handler
MemorySize: 128
Role: !GetAtt LambdaExecutionRole.Arn
Runtime: 'python3.6'
Timeout: 30
Code:
ZipFile: |
import boto3
import cfnresponse
import uuid
import json
def handler(event, context):
responseData = {}
responseData['StackId'] = event['StackId']
responseData['RequestId'] = event['RequestId']
responseData['LogicalResourceId'] = event['LogicalResourceId']
if event['RequestType'] == 'Delete':
responseData['Status'] = cfnresponse.SUCCESS
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
return
# Since we are creating or updating the resource, create a new
# PhysicalResourceId.
responseData['PhysicalResourceId'] = (
'VpcEndpointServiceAZs' +
str(uuid.uuid1())
)
try:
desiredNumAzsStr = event['ResourceProperties']['DesiredNumAzs']
desiredNumAzs = int(desiredNumAzsStr)
except:
responseData['Status'] = cfnresponse.FAILED
responseData['Reason'] = (
'DesiredNumAzs is required and must be a whole number'
)
print(responseData['Reason'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
return
if desiredNumAzs < 0:
responseData['Status'] = cfnresponse.FAILED
responseData['Reason'] = (
'DesiredNumAzs is required and must be a whole number'
)
print(responseData['Reason'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
return
try:
ec2=boto3.client('ec2')
except:
responseData['Status'] = cfnresponse.FAILED
responseData['Reason'] = 'unable to set up ec2 client'
print(responseData['Reason'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
return
try:
serviceName = event['ResourceProperties']['ServiceName']
response = ec2.describe_vpc_endpoint_services(
ServiceNames = [ serviceName ]
)
except:
responseData['Status'] = cfnresponse.FAILED
responseData['Reason'] = 'unable to rerieve endpoint service info'
print(responseData['Reason'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
return
print(json.dumps(response))
numberOfServices = len(response['ServiceDetails'])
if numberOfServices != 1:
responseData['Status'] = cfnresponse.FAILED
responseData['Reason'] = (
'number of services should be 1 but is: ' +
str(numberOfServices)
)
print(responseData['Reason'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
return
Azs = response['ServiceDetails'][0]['AvailabilityZones']
numAzs = len(Azs)
if numAzs < desiredNumAzs:
responseData['Status'] = cfnresponse.FAILED
responseData['Reason'] = (
'insufficient number of availability zones - found: ' +
str(numAzs)
)
print(responseData['Reason'])
cfnresponse.send(event, context, cfnresponse.FAILED, responseData)
return
responseData['Status'] = cfnresponse.SUCCESS
responseData['NumAzs'] = str(numAzs)
responseData['Azs'] = ','.join(Azs)
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData)
return
# VpcEndpointSeviceAzsLogGroup - CloudWatch Logs log group for
# VpcEndPointServiceAzsFunction
VpcEndpointServiceAzsLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Join [ '', [ '/aws/lambda/', Ref: VpcEndpointServiceAzsFunction ] ]
RetentionInDays: 1
# SecretsManagerAzs: Look up the AZs that offer AWS Secrets Manager interface
# endpoints
SecretsManagerAzs:
Type: Custom::SecretsManagerAzs
DependsOn: VpcEndpointServiceAzsLogGroup
Properties:
ServiceToken: !GetAtt VpcEndpointServiceAzsFunction.Arn
ServiceName:
!Join
- ''
- - 'com.amazonaws.'
- !Ref 'AWS::Region'
- '.secretsmanager'
DesiredNumAzs: 2
# SessionManagerAzs: Look up the AZs that offer AWS Systems Manager interface
# endpoints
SessionManagerAzs:
Type: Custom::SessionManagerAzs
DependsOn: VpcEndpointServiceAzsLogGroup
Properties:
ServiceToken: !GetAtt VpcEndpointServiceAzsFunction.Arn
ServiceName:
!Join
- ''
- - 'com.amazonaws.'
- !Ref 'AWS::Region'
- '.ssmmessages'
DesiredNumAzs: 2
# SecretsMgrSubnet01 and SecretsMgrSubnet02 - Note that the EC2 and
# RDS instances will only go into SecretsMgrSubnet01. We need, however, another
# subnet for the DB subnet group regardless.
SecretsMgrSubnet01:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [0, !Split [",", !GetAtt SecretsManagerAzs.Azs]]
CidrBlock:
!Join
- ''
- - !Ref VpcCidrOctet1
- '.'
- !Ref VpcCidrOctet2
- '.11.0/24'
MapPublicIpOnLaunch: 'true'
Tags:
- Key: Name
Value: !Join [ '', [ Ref: NamePrefix, '-secretsmgrsn01' ]]
- Key: Project
Value: !Ref ProjectTag
VpcId: !Ref Vpc
SecretsMgrSubnet02:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [1, !Split [",", !GetAtt SecretsManagerAzs.Azs]]
CidrBlock:
!Join
- ''
- - !Ref VpcCidrOctet1
- '.'
- !Ref VpcCidrOctet2
- '.12.0/24'
MapPublicIpOnLaunch: 'true'
Tags:
- Key: Name
Value: !Join [ '', [ Ref: NamePrefix, '-secretsmgrsn02' ]]
- Key: Project
Value: !Ref ProjectTag
VpcId: !Ref Vpc
# SessionMgrSubnet01 and 02: Subnets for the Session Manaager Endpoint
SessionMgrSubnet01:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [0, !Split [",", !GetAtt SessionManagerAzs.Azs]]
CidrBlock:
!Join
- ''
- - !Ref VpcCidrOctet1
- '.'
- !Ref VpcCidrOctet2
- '.21.0/24'
MapPublicIpOnLaunch: 'true'
Tags:
- Key: Name
Value: !Join [ '', [ Ref: NamePrefix, '-sessmgrsn01' ]]
- Key: Project
Value: !Ref ProjectTag
VpcId: !Ref Vpc
SessionMgrSubnet02:
Type: AWS::EC2::Subnet
Properties:
AvailabilityZone: !Select [1, !Split [",", !GetAtt SessionManagerAzs.Azs]]
CidrBlock:
!Join
- ''
- - !Ref VpcCidrOctet1
- '.'
- !Ref VpcCidrOctet2
- '.22.0/24'
MapPublicIpOnLaunch: 'true'
Tags:
- Key: Name
Value: !Join [ '', [ Ref: NamePrefix, '-sessmgrsn01' ]]
- Key: Project
Value: !Ref ProjectTag
VpcId: !Ref Vpc
# Associate subnets with the routng table.
SecretsMgrSubnet01Rtb:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: VpcIgwAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref SecretsMgrSubnet01
SecretsMgrSubnet02Rtb:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: VpcIgwAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref SecretsMgrSubnet02
SessionMgrSubnet01Rtb:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: VpcIgwAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref SessionMgrSubnet01
SessionMgrSubnet02Rtb:
Type: AWS::EC2::SubnetRouteTableAssociation
DependsOn: VpcIgwAttachment
Properties:
RouteTableId: !Ref PublicRouteTable
SubnetId: !Ref SessionMgrSubnet02
Outputs:
VpcId:
Value: !Ref Vpc
Export:
Name: VpcId
PublicRouteTableId:
Value: !Ref PublicRouteTable
Export:
Name: PublicRouteTableId
SecretsMgrSubnet01Id:
Value: !Ref SecretsMgrSubnet01
Export:
Name: SecretsMgrSubnet01Id
SecretsMgrSubnet01Az:
Value: !GetAtt SecretsMgrSubnet01.AvailabilityZone
Export:
Name: SecretsMgrSubnet01Az
SecretsMgrSubnet02Id:
Value: !Ref SecretsMgrSubnet02
Export:
Name: SecretsMgrSubnet02Id
SecretsMgrSubnet02Az:
Value: !GetAtt SecretsMgrSubnet02.AvailabilityZone
Export:
Name: SecretsMgrSubnet02Az
SessionMgrSubnet01Id:
Value: !Ref SessionMgrSubnet01
Export:
Name: SessionMgrSubnet01Id
SessionMgrSubnet01Az:
Value: !GetAtt SessionMgrSubnet01.AvailabilityZone
Export:
Name: SessionMgrSubnet01Az
SessionMgrSubnet02Id:
Value: !Ref SessionMgrSubnet02
Export:
Name: SessionMgrSubnet02Id
SessionMgrSubnet02Az:
Value: !GetAtt SessionMgrSubnet02.AvailabilityZone
Export:
Name: SessionMgrSubnet02Az
NamePrefix:
Value: !Ref NamePrefix
Export:
Name: NamePrefix
ProjectTag:
Value: !Ref ProjectTag
Export:
Name: ProjectTag
VpcCidrOctet1:
Value: !Ref VpcCidrOctet1
Export:
Name: VpcCidrOctet1
VpcCidrOctet2:
Value: !Ref VpcCidrOctet2
Export:
Name: VpcCidrOctet2