forked from ministryofjustice/bootstrap-cfn
/
config.py
1604 lines (1406 loc) · 61.5 KB
/
config.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
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datadiff
import copy
import json
import logging
import os
import sys
import textwrap
from fabric.api import env
from fabric.colors import green
import netaddr
from troposphere import Base64, FindInMap, GetAZs, GetAtt, Join, Output, Ref, Tags, Template
from troposphere.autoscaling import AutoScalingGroup, BlockDeviceMapping, \
EBSBlockDevice, LaunchConfiguration, Tag
from troposphere.certificatemanager import Certificate, DomainValidationOption
from troposphere.ec2 import InternetGateway, Route, RouteTable, SecurityGroup, \
SecurityGroupIngress, Subnet, SubnetRouteTableAssociation, VPC, \
VPCGatewayAttachment
from troposphere.elasticache import ReplicationGroup, SubnetGroup
from troposphere.elasticloadbalancing import ConnectionDrainingPolicy, \
HealthCheck, LoadBalancer, Policy
from troposphere.iam import InstanceProfile, PolicyType, Role
from troposphere.rds import DBInstance, DBSubnetGroup
from troposphere.route53 import AliasTarget, RecordSet, RecordSetGroup
from troposphere.s3 import Bucket, BucketPolicy, LifecycleConfiguration, \
LifecycleRule
import yaml
from bootstrap_cfn import errors, mime_packer, utils, vpc, diff
class ProjectConfig:
config = None
def __init__(self,
config,
environment,
passwords=None,
defaults=os.path.join(os.path.dirname(__file__), 'config_defaults.yaml')):
try:
self.config = {}
# Load all the necessary config files and defaults
config_defaults = self.load_yaml(defaults).get(environment,
self.load_yaml(defaults)['default'])
user_config = self.load_yaml(config)[environment]
passwords_config = {}
if passwords:
passwords_config = self.load_yaml(passwords).get(environment, {})
# Validate all the settings we have loaded in
logging.info('bootstrap-cfn:: Validating default settings for environment %s in file %s'
% (environment, defaults))
self.validate_configuration_settings(config_defaults)
logging.info('bootstrap-cfn:: Validating user settings for environment %s in file %s'
% (environment, config))
self.validate_configuration_settings(user_config)
logging.info('bootstrap-cfn:: Validating passwords settings for environment %s in file %s'
% (environment, passwords))
self.validate_configuration_settings(passwords_config)
# Collect together all the config keys the user has specified
all_user_config_keys = set(user_config.keys()) | set(passwords_config.keys())
# Only set configuration settings where we have specified that component in the user config
# This means we only get non-required components RDS, elasticache, etc if we have requested them
for config_key in all_user_config_keys:
# we're going to merge in order of,
# defaults <- user_config <- secrets_config
# Catch badly formatted yaml where we get NoneType values,
# merging in these will overwrite all the other config
self.config[config_key] = config_defaults.get(config_key, {})
# Overwrite defaults with user_config values
self.config[config_key] = utils.dict_merge(self.config[config_key],
user_config.get(config_key, {}))
# Overwrite user config with password config values
self.config[config_key] = utils.dict_merge(self.config[config_key],
passwords_config.get(config_key, {}))
except KeyError:
raise errors.BootstrapCfnError("Environment " + environment + " not found")
@staticmethod
def load_yaml(fp):
if os.path.exists(fp):
return yaml.load(open(fp).read())
@staticmethod
def validate_configuration_settings(configuration_settings):
"""
Run some sanity checks on the configuration settings we're going to use
Args:
config: The settings object we want to validate
Raises:
CfnConfigError
"""
# Basic settings checks
# settings should be a dictionary
if not isinstance(configuration_settings, dict):
raise errors.CfnConfigError("Configuration settings are not in dictionary format")
for key, value in configuration_settings.iteritems():
# No base keys should have a None value
if value is None:
raise errors.CfnConfigError("Configuration key value %s is None."
% (key))
class ConfigParser(object):
config = {}
def __init__(self, data, stack_name, environment=None, application=None, keyname=None):
self.stack_name = stack_name
self.data = data
self.stack_id = self.stack_name.split('-')[-1]
# Some things possibly used in user data templates
self.environment = environment
self.application = application
self.keyname = keyname
def process_update(self, templatebody):
pristine = json.loads(templatebody)
#
# Prepare the new template.
#
#
# Here be dragons!
#
# the gateway attachment referencing the InternetGateway and
# VPC needs to exist before calling ec2() and elb() on the
# template.
#
# If you change the name of the VPC or the IGW on the CF
# template, the below will need to change to reflect the
# change.
#
template = Template()
gw_attachment = VPCGatewayAttachment(
"AttachGateway",
VpcId=Ref('VPC'),
InternetGatewayId=Ref('InternetGateway'),
DependsOn='InternetGateway'
)
template.add_resource(gw_attachment)
if pristine['Resources'].get("DatabaseSG", None):
database_sg = SecurityGroup(
"DatabaseSG",
SecurityGroupIngress=[
{"ToPort": 5432,
"FromPort": 5432,
"IpProtocol": "tcp",
"CidrIp": FindInMap("SubnetConfig", "VPC", "CIDR")},
{"ToPort": 1433,
"FromPort": 1433,
"IpProtocol": "tcp",
"CidrIp": FindInMap("SubnetConfig", "VPC", "CIDR")},
{"ToPort": 3306,
"FromPort": 3306,
"IpProtocol": "tcp",
"CidrIp": FindInMap("SubnetConfig", "VPC", "CIDR")}
],
VpcId=Ref("VPC"),
GroupDescription="SG for EC2 Access to RDS",
# translates to DependsOn=["AttachGateway"],
# but if not, ensure the tests have been updated too
DependsOn=[
r.title
for r in self._find_resources(
template, "AWS::EC2::VPCGatewayAttachment")],
)
template.add_resource(database_sg)
ec2 = self.ec2()
map(template.add_resource, ec2)
self.elb(template)
template = json.loads(template.to_json())
# Copy new entries on top of the old ones
temp = copy.deepcopy(pristine)
for i in template.get('Resources', []):
temp['Resources'][i] = template['Resources'][i]
for i in template.get('Outputs', []):
temp['Outputs'][i] = template['Outputs'][i]
#
# Delete stale LoadBalancer (ELBname) entries and
# SecurityGroups (name is configued on yaml) from CF Resources
#
# This cover cases where we rename elbs and security groups.
#
deleted_resources = utils.delete_stale_types(temp['Resources'], template['Resources'],
'AWS::ElasticLoadBalancing::LoadBalancer')
ec2_sg_resources = utils.delete_stale_types(temp['Resources'], template['Resources'],
'AWS::EC2::SecurityGroup')
# Manual cleanup
#
# Each old ELBname had a Policyname and a DNSname entry
# attached to the CFN but not directly referenced with
# 'Ref'. Remove them as well.
#
if deleted_resources is not None:
dns_cleanup = map(lambda i:i.replace('ELB', 'DNS'), deleted_resources)
policy_cleanup = map(lambda i:i.replace('ELB', 'Policy'), deleted_resources)
# Deleting resources.
for i in dns_cleanup + policy_cleanup:
try:
del temp['Resources'][i]
except:
logging.debug('{0} not found in Resources section'.format(i))
# Deleting outputs
for i in deleted_resources:
try:
del temp['Outputs'][i]
except:
logging.debug('{0} not found in Outputs section'.format(i))
logging.debug('Resources to be removed: {}'.format(deleted_resources, dns_cleanup, policy_cleanup, ec2_sg_resources))
logging.debug('Outputs to be removed: {}'.format(deleted_resources))
# Diff method 1
# print a non cloudformation context diff
changes = diff.diff(pristine, temp)
logging.info(changes)
# Diff method 2
changes = datadiff.diff(pristine, temp)
logging.info(changes)
# convert the result to json
result = json.dumps(temp, sort_keys=True, indent=None, separators=(',', ': '))
return result
def process(self):
template = self.base_template()
vpc = self.vpc()
map(template.add_resource, vpc)
iam = self.iam()
map(template.add_resource, iam)
ec2 = self.ec2()
map(template.add_resource, ec2)
if 'elb' in self.data:
self.elb(template)
if 'rds' in self.data:
self.rds(template)
if 'elasticache' in self.data:
self.elasticache(template)
if 's3' in self.data:
self.s3(template)
template = json.loads(template.to_json())
if 'includes' in self.data:
for inc_path in self.data['includes']:
inc = json.load(open(inc_path))
template = utils.dict_merge(template, inc)
return json.dumps(
template, sort_keys=True, indent=None, separators=(',', ': '))
def base_template(self):
t = Template()
# Get the OS specific data
os_data = self._get_os_data()
t.add_mapping("AWSRegion2AMI", {
os_data.get('region'): {"AMI": os_data.get('ami')},
})
# If we have a cidr defined, use that, else dynamically retrieve it
vpc_cidr = None
subnets_defined = False
if 'vpc' in self.data and len(self.data.get('vpc', {})) > 0:
logging.info("config::base_template: Found VPC config section")
vpc_data = self.data.get('vpc', {})
vpc_cidr = vpc_data.get('CIDR')
# Check for manually defined subnets
subnet_names = self._get_subnet_names()
vpc_subnet_config = {}
vpc_subnet_config["VPC"] = {}
vpc_subnet_config['VPC']['CIDR'] = vpc_cidr
count = 0
for subnet_name in subnet_names:
subnet_entry = vpc_data.get(subnet_name, None)
if subnet_entry is not None:
logging.info("config::base_template: Found VPC subnet {}"
.format(subnet_entry))
vpc_subnet_config['VPC'][subnet_name] = subnet_entry
subnets_defined = True
count += 1
if not subnets_defined:
logging.info("config::base_template: No VPC config or subnets found, "
"using dynamic setup")
vpc_subnet_config = self._get_vpc_subnet_config(vpc_cidr)
t.add_mapping("SubnetConfig", vpc_subnet_config)
return t
def vpc(self):
resources = []
vpc = VPC(
"VPC",
InstanceTenancy="default",
EnableDnsSupport="true",
CidrBlock=FindInMap("SubnetConfig", "VPC", "CIDR"),
EnableDnsHostnames="true",
)
resources.append(vpc)
igw = InternetGateway(
"InternetGateway",
Tags=Tags(
Application=Ref("AWS::StackId"),
Network="Public",
),
DependsOn=vpc.title,
)
resources.append(igw)
gw_attachment = VPCGatewayAttachment(
"AttachGateway",
VpcId=Ref(vpc),
InternetGatewayId=Ref(igw),
DependsOn=igw.title
)
resources.append(gw_attachment)
route_table = RouteTable(
"PublicRouteTable",
VpcId=Ref(vpc),
Tags=Tags(
Application=Ref("AWS::StackId"),
Network="Public",
),
)
resources.append(route_table)
public_route = Route(
"PublicRoute",
GatewayId=Ref(igw),
DestinationCidrBlock="0.0.0.0/0",
RouteTableId=Ref(route_table),
DependsOn=gw_attachment.title
)
resources.append(public_route)
subnet_names = self._get_subnet_names(env.aws_region)
for subnet_name in subnet_names:
subnet = Subnet(
subnet_name,
VpcId=Ref(vpc),
AvailabilityZone=subnet_names.get(subnet_name),
CidrBlock=FindInMap("SubnetConfig", "VPC", subnet_name),
Tags=Tags(
Application=Ref("AWS::StackId"),
Network="Public",
),
)
resources.append(subnet)
route_association_name = ("{}RouteTableAssociation"
.format(subnet_name))
subnet_route_assoc = SubnetRouteTableAssociation(
route_association_name,
SubnetId=Ref(subnet),
RouteTableId=Ref(route_table),
)
resources.append(subnet_route_assoc)
# Hack until we return troposphere objects directly
# return json.loads(json.dumps(dict((r.title, r) for r in resources), cls=awsencode))
return resources
def iam(self):
role = Role(
"BaseHostRole",
Path="/",
AssumeRolePolicyDocument={
"Statement": [{
"Action": ["sts:AssumeRole"],
"Effect": "Allow",
"Principal": {"Service": ["ec2.amazonaws.com"]}
}]
},
)
# Set required policy actions
# elasticloadbalancing:Describe* "*" needed for aws-formula and cron-formula
policy_actions = [{"Action": ["autoscaling:Describe*"], "Resource": "*", "Effect": "Allow"},
{"Action": ["cloudformation:Describe*"], "Resource": "*", "Effect": "Allow"},
{"Action": ["elasticloadbalancing:Describe*"], "Resource": "*", "Effect": "Allow"}]
# Only define policy actions if the components are enabled in the config
if 'ec2' in self.data:
policy_actions.append({"Action": ["ec2:Describe*"], "Resource": "*", "Effect": "Allow"})
policy_actions.append({"Action": ["ec2:CreateTags"], "Resource": "*", "Effect": "Allow"})
if 'rds' in self.data:
policy_actions.append({"Action": ["rds:Describe*"], "Resource": "*", "Effect": "Allow"})
if 'elasticache' in self.data:
policy_actions.append({"Action": ["elasticache:Describe*"], "Resource": "*", "Effect": "Allow"})
if 's3' in self.data:
policy_actions.append({"Action": ["s3:List*"], "Resource": "*", "Effect": "Allow"})
role_policies = PolicyType(
"RolePolicies",
PolicyName="BaseHost",
PolicyDocument={"Statement": policy_actions},
Roles=[Ref(role)],
)
instance_profile = InstanceProfile(
"InstanceProfile",
Path="/",
Roles=[Ref(role)],
)
resources = [role, role_policies, instance_profile]
# Hack until we return troposphere objects directly
# return json.loads(json.dumps(dict((r.title, r) for r in resources), cls=awsencode))
return resources
def s3(self, template):
"""
Create an s3 resource configuration from the config file data.
This will produce Bucket and BucketPolicy resources along with
the bucket name as output, these are all added to the troposphere
template.
Args:
template:
The troposphere.Template object
"""
# As there are no required fields, although we may not have any
# subkeys we still need to be able to have a parent key 's3:' to
# signify that we want to create an s3 bucket. In this case we
# set up an empty (no options set) dictionary
present_keys = {}
if isinstance(self.data['s3'], dict):
present_keys = self.data['s3'].keys()
# Enable specifying multiple buckets
if 'buckets' in present_keys:
bucket_list = self.data['s3'].get('buckets')
for bucket_config in bucket_list:
self.create_s3_bucket(bucket_config, template)
# If the static bucket name is manually set then use that,
# otherwise use the <stackname>-<logical-resource-name>-<random>
# default
bucket = Bucket(
"StaticBucket",
AccessControl="BucketOwnerFullControl",
)
if 'static-bucket-name' in present_keys:
bucket.BucketName = self.data['s3']['static-bucket-name']
# If a policy has been manually set then use it, otherwise set
# a reasonable default of public 'Get' access
if 'policy' in present_keys:
policy = json.loads(open(self.data['s3']['policy']).read())
else:
arn = Join("", ["arn:aws:s3:::", Ref(bucket), "/*"])
policy = {
'Action': ['s3:GetObject'],
"Resource": arn,
'Effect': 'Allow',
'Principal': '*'}
bucket_policy = BucketPolicy(
"StaticBucketPolicy",
Bucket=Ref(bucket),
PolicyDocument={"Statement": [policy]},
)
# Add the bucket name to the list of cloudformation
# outputs
template.add_output(Output(
"StaticBucketName",
Description="S3 bucket name",
Value=Ref(bucket)
))
# Add the resources to the troposphere template
map(template.add_resource, [bucket, bucket_policy])
def create_s3_bucket(self, bucket_config, template):
"""
Create an s3 bucket configuration from config data.
This will produce Bucket and BucketPolicy resources along with
the bucket name as output, these are all added to the troposphere
template.
Args:
bucket_config(dictionary): Keyed bucket config settings
template:
The troposphere.Template object
"""
bucket_name = bucket_config.get('name')
if 'lifecycles' in bucket_config:
lifecycle_cfg = self.create_s3_lifecyclerules(bucket_config['lifecycles'])
bucket = Bucket(
bucket_name,
AccessControl="BucketOwnerFullControl",
LifecycleConfiguration=lifecycle_cfg
)
else:
bucket = Bucket(
bucket_name,
AccessControl="BucketOwnerFullControl"
)
# If a policy has been manually set then use it, otherwise set
# a reasonable default of public 'Get' access
if 'policy' in bucket_config:
policy = json.loads(open(bucket_config['policy']).read())
else:
arn = Join("", ["arn:aws:s3:::", Ref(bucket), "/*"])
policy = {
'Action': ['s3:DeleteObject', 's3:GetObject', 's3:PutObject'],
"Resource": arn,
'Effect': 'Allow',
'Principal': '*',
"Condition": {
"StringEquals": {
"aws:sourceVpc": {"Ref": "VPC"}
}
}
}
policy = policy if isinstance(policy, list) else [policy]
bucket_policy = BucketPolicy(
"{}Policy".format(bucket_name),
Bucket=Ref(bucket),
PolicyDocument={"Statement": policy},
)
# Add the bucket name to the list of cloudformation
# outputs
template.add_output(Output(
"{}BucketName".format(bucket_name),
Description="S3 bucket name",
Value=Ref(bucket)
))
map(template.add_resource, [bucket, bucket_policy])
def create_s3_lifecyclerules(self, rules):
if not rules:
raise errors.CfnConfigError("No expiration rules defines for lifecycles attribute")
try:
root = rules.pop('/')
except KeyError:
root = None
r = []
if root:
expiration = self._validate_s3_lifecycles(root)
logging.debug("Root directory lifecycle rule detected. Ignoring other rules if defined.")
r.append(LifecycleRule(Id="lifecyclerule_root",
Status="Enabled",
ExpirationInDays=expiration))
else:
for directory in rules:
expiration = self._validate_s3_lifecycles(rules[directory])
r.append(LifecycleRule(Id="lifecyclerule_{0}".format(self._get_alphanumeric_name(directory)),
Prefix=directory,
Status="Enabled",
ExpirationInDays=expiration))
lifecycle_cfg = LifecycleConfiguration(Rules=r)
return lifecycle_cfg
def _validate_s3_lifecycles(self, rule):
if type(rule) is not dict:
raise errors.CfnConfigError("Prefixes defined under lifecycles attribute must be dictionaries")
try:
expiration = int(rule.get('expirationdays'))
except KeyError:
raise errors.CfnConfigError("No expiration length defined in s3 lifecycle")
except:
raise errors.CfnConfigError("Expiration length is ill defined in s3 lifecycle: other error")
return expiration
def ssl(self):
return self.data.get('ssl', {})
def rds(self, template):
"""
Create an RDS resource configuration from the config file data
and add it to the troposphere.Template. Outputs for the RDS name,
host and port are created.
Args:
template:
The troposphere.Template object
"""
# REQUIRED FIELDS MAPPING
required_fields = {
'db-name': 'DBName',
'db-master-username': 'MasterUsername',
'db-master-password': 'MasterUserPassword',
}
optional_fields = {
'storage': 'AllocatedStorage',
'storage-type': 'StorageType',
'backup-retention-period': 'BackupRetentionPeriod',
'db-engine': 'Engine',
'db-engine-version': 'EngineVersion',
'instance-class': 'DBInstanceClass',
'multi-az': 'MultiAZ',
'storage-encrypted': 'StorageEncrypted',
'identifier': 'DBInstanceIdentifier'
}
# LOAD STACK TEMPLATE
resources = []
rds_subnet_group = DBSubnetGroup(
"RDSSubnetGroup",
SubnetIds=self._get_subnet_refs(env.aws_region),
DBSubnetGroupDescription="VPC Subnets"
)
resources.append(rds_subnet_group)
database_sg = SecurityGroup(
"DatabaseSG",
SecurityGroupIngress=[
{"ToPort": 5432,
"FromPort": 5432,
"IpProtocol": "tcp",
"CidrIp": FindInMap("SubnetConfig", "VPC", "CIDR")},
{"ToPort": 1433,
"FromPort": 1433,
"IpProtocol": "tcp",
"CidrIp": FindInMap("SubnetConfig", "VPC", "CIDR")},
{"ToPort": 3306,
"FromPort": 3306,
"IpProtocol": "tcp",
"CidrIp": FindInMap("SubnetConfig", "VPC", "CIDR")}
],
VpcId=Ref("VPC"),
GroupDescription="SG for EC2 Access to RDS",
# translates to DependsOn=["AttachGateway"],
# but if not, ensure the tests have been updated too
DependsOn=[
r.title
for r in self._find_resources(
template, "AWS::EC2::VPCGatewayAttachment")],
)
resources.append(database_sg)
rds_instance = DBInstance(
"RDSInstance",
PubliclyAccessible=False,
AllowMajorVersionUpgrade=False,
AutoMinorVersionUpgrade=False,
VPCSecurityGroups=[GetAtt(database_sg, "GroupId")],
DBSubnetGroupName=Ref(rds_subnet_group),
DependsOn=database_sg.title
)
resources.append(rds_instance)
# We *cant* specify db-name for SQL Server based RDS instances. :(
if 'db-engine' in self.data['rds'] and self.data['rds']['db-engine'].startswith("sqlserver"):
required_fields.pop('db-name')
if 'identifier' in self.data['rds']:
# update identifier name
self.data['rds']['identifier'] = "{}-{}".format(self.data['rds']['identifier'], self.stack_id)
# logging.info("identifier was updated to {}".format(self.data['rds']['identifier']))
print green("identifier was updated to {}".format(self.data['rds']['identifier']))
# TEST FOR REQUIRED FIELDS AND EXIT IF MISSING ANY
for yaml_key, rds_prop in required_fields.iteritems():
if yaml_key not in self.data['rds']:
print "\n\n[ERROR] Missing RDS fields [%s]" % yaml_key
sys.exit(1)
else:
rds_instance.__setattr__(rds_prop, self.data['rds'][yaml_key])
for yaml_key, rds_prop in optional_fields.iteritems():
if yaml_key in self.data['rds']:
rds_instance.__setattr__(rds_prop, self.data['rds'][yaml_key])
# Add resources and outputs
map(template.add_resource, resources)
template.add_output(Output(
"dbhost",
Description="RDS Hostname",
Value=GetAtt(rds_instance, "Endpoint.Address")
))
template.add_output(Output(
"dbport",
Description="RDS Port",
Value=GetAtt(rds_instance, "Endpoint.Port")
))
def elasticache(self, template):
"""
Create an elasticache resource configuration from the config file data
and add it to the troposphere.Template. Outputs for the elasticache name,
host and port are created.
Args:
template:
The troposphere.Template object
"""
# REQUIRED FIELDS MAPPING
required_fields = {
}
optional_fields = {
'clusters': 'NumCacheClusters',
'node_type': 'CacheNodeType',
'port': 'Port',
}
# Generate snapshot arns
seeds = self.data['elasticache'].get('seeds', None)
snapshot_arns = []
if seeds:
# Get s3 seeds
s3_seeds = seeds.get('s3', [])
for seed in s3_seeds:
snapshot_arns.append("arn:aws:s3:::%s" % (seed))
# LOAD STACK TEMPLATE
resources = []
es_sg = SecurityGroup(
"ElasticacheSG",
SecurityGroupIngress=[
{"ToPort": self.data['elasticache']['port'],
"FromPort": self.data['elasticache']['port'],
"IpProtocol": "tcp",
"CidrIp": FindInMap("SubnetConfig", "VPC", "CIDR")}
],
VpcId=Ref("VPC"),
GroupDescription="SG for EC2 Access to Elasticache",
)
resources.append(es_sg)
es_subnet_group = SubnetGroup(
'ElasticacheSubnetGroup',
Description="Elasticache Subnet Group",
SubnetIds=self._get_subnet_refs(env.aws_region)
)
resources.append(es_subnet_group)
elasticache_replication_group = ReplicationGroup(
"ElasticacheReplicationGroup",
ReplicationGroupDescription='Elasticache Replication Group',
Engine=self.data['elasticache'].get('engine'),
NumCacheClusters=self.data['elasticache']['clusters'],
CacheNodeType=self.data['elasticache']['node_type'],
SecurityGroupIds=[GetAtt(es_sg, "GroupId")],
CacheSubnetGroupName=Ref(es_subnet_group),
SnapshotArns=snapshot_arns
)
resources.append(elasticache_replication_group)
# TEST FOR REQUIRED FIELDS AND EXIT IF MISSING ANY
for yaml_key, prop in required_fields.iteritems():
if yaml_key not in self.data['elasticache']:
print "\n\n[ERROR] Missing Elasticache fields [%s]" % yaml_key
sys.exit(1)
else:
elasticache_replication_group.__setattr__(prop, self.data['elasticache'][yaml_key])
for yaml_key, prop in optional_fields.iteritems():
if yaml_key in self.data['elasticache']:
elasticache_replication_group.__setattr__(prop, self.data['elasticache'][yaml_key])
# Add resources and outputs
map(template.add_resource, resources)
template.add_output(Output(
"ElasticacheReplicationGroupName",
Description="Elasticache Replication Group Name",
Value=Ref(elasticache_replication_group)
))
template.add_output(Output(
"ElasticacheEngine",
Description="Elasticache Engine",
Value=self.data['elasticache'].get('engine')
))
def elb(self, template):
"""
Create an ELB resource configuration from the config file data
and add them to the troposphere template. Outputs for each ELB's
DNSName are created.
Args:
template:
The cloudformation template file
"""
# REQUIRED FIELDS AND MAPPING
# Note, 'name' field is used internally to help label
# logical ids, and as part of the DNS record name.
required_fields = {
'listeners': 'Listeners',
'scheme': 'Scheme',
'name': None,
'hosted_zone': 'HostedZoneName'
}
elb_list = []
elb_sgs = []
# COULD HAVE MULTIPLE ELB'S (PUBLIC / PRIVATE etc)
for elb in self.data['elb']:
safe_name = elb['name'].replace('-', '').replace('.', '').replace('_', '')
# TEST FOR REQUIRED FIELDS AND EXIT IF MISSING ANY
for i in required_fields.keys():
if i not in elb.keys():
print "\n\n[ERROR] Missing ELB fields [%s]" % i
sys.exit(1)
# Collect together all policies
elb_policies = [
Policy(
Attributes=[{'Name': "Reference-Security-Policy", 'Value': "ELBSecurityPolicy-2015-05"}],
PolicyType='SSLNegotiationPolicyType',
PolicyName='PinDownSSLNegotiationPolicy201505'
)]
for custom_policy_config in elb.get('policies', []):
custom_policy_name = custom_policy_config.get('name', False)
custom_policy_type = custom_policy_config.get('type', False)
if not custom_policy_name:
logging.critical("config::elb: Load balancer policy must have a name defined")
sys.exit(1)
if not custom_policy_type:
logging.critical("config::elb: Load balancer policy {} must have a type defined".format(custom_policy_name))
sys.exit(1)
custom_policy_attributes = []
for custom_policy_attribute_config in custom_policy_config.get('attributes', []):
for custom_policy_attribute_key, custom_policy_attribute_val in custom_policy_attribute_config.iteritems():
custom_policy_attributes_entry = {
'Name': custom_policy_attribute_key,
'Value': custom_policy_attribute_val
}
custom_policy_attributes.append(custom_policy_attributes_entry)
custom_policy = Policy(
Attributes=custom_policy_attributes,
PolicyType=custom_policy_type,
PolicyName=custom_policy_name,
)
# Dont set these unless theyre in the config, other CFN will break
if custom_policy_config.get('instance_ports', False):
custom_policy.InstancePorts = custom_policy_config.get('instance_ports')
if custom_policy_config.get('load_balancer_ports', False):
custom_policy.LoadBalancerPorts = custom_policy_config.get('load_balancer_ports')
elb_policies.append(custom_policy)
load_balancer = LoadBalancer(
"ELB" + safe_name,
Subnets=self._get_subnet_refs(env.aws_region),
Listeners=elb['listeners'],
Scheme=elb['scheme'],
ConnectionDrainingPolicy=ConnectionDrainingPolicy(
Enabled=True,
Timeout=120,
),
Policies=elb_policies
)
if elb['scheme'] == 'internet-facing':
vpc_gw_att = [
r.title
for r in self._find_resources(
template, "AWS::EC2::VPCGatewayAttachment")]
# if a VPCGatewayAttachment exists in template make the ELB depend on it
# because ELB is public/internet facing and needs Internet Gateway
if vpc_gw_att:
load_balancer.DependsOn = vpc_gw_att
if "health_check" in elb:
load_balancer.HealthCheck = HealthCheck(**elb['health_check'])
for listener in load_balancer.Listeners:
if listener['Protocol'] == 'HTTPS':
listener["SSLCertificateId"] = self._get_ssl_certificate(template, elb.get('certificate_name', None))
# if not present, add the default cipher policy
if 'PolicyNames' not in listener:
logging.debug(
"ELB Listener for port 443 has no SSL Policy. " +
"Using default ELBSecurityPolicy-2015-05")
listener['PolicyNames'] = ['PinDownSSLNegotiationPolicy201505']
elb_list.append(load_balancer)
dns_record = RecordSetGroup(
"DNS" + safe_name,
HostedZoneName=elb['hosted_zone'],
Comment="Zone apex alias targeted to ElasticLoadBalancer.",
RecordSets=[
RecordSet(
"TitleIsIgnoredForThisResource",
Name="%s-%s.%s" % (elb['name'], self.stack_id, elb['hosted_zone']),
Type="A",
AliasTarget=AliasTarget(
GetAtt(load_balancer, "CanonicalHostedZoneNameID"),
GetAtt(load_balancer, "DNSName"),
),
),
]
)
elb_list.append(dns_record)
elb_role_policies = PolicyType(
"Policy" + safe_name,
PolicyName=safe_name + "BaseHost",
PolicyDocument={"Statement": [{
"Action": [
"elasticloadbalancing:DeregisterInstancesFromLoadBalancer",
"elasticloadbalancing:RegisterInstancesWithLoadBalancer"
],
"Resource": [
Join("", [
"arn:aws:elasticloadbalancing:",
Ref("AWS::Region"),
":",
Ref("AWS::AccountId"),
':loadbalancer/',
Ref(load_balancer)
])
],
"Effect": "Allow"}
]},
Roles=[Ref("BaseHostRole")],
)
elb_list.append(elb_role_policies)
if "security_groups" in elb:
load_balancer.SecurityGroups = []
for sg_name, sg_rules in elb['security_groups'].items():
sg = SecurityGroup(
sg_name,
GroupDescription=sg_name,
SecurityGroupIngress=sg_rules,
VpcId=Ref("VPC")
)
load_balancer.SecurityGroups.append(Ref(sg))
elb_sgs.append(sg)
else:
sg = SecurityGroup(
"DefaultSG" + safe_name,
GroupDescription="DefaultELBSecurityGroup",
SecurityGroupIngress=[
{
"IpProtocol": "tcp",
"FromPort": 443,
"ToPort": 443,
"CidrIp": "0.0.0.0/0"
},
{
"IpProtocol": "tcp",
"FromPort": 80,
"ToPort": 80,
"CidrIp": "0.0.0.0/0"
}
],
VpcId=Ref("VPC")
)
load_balancer.SecurityGroups = [Ref(sg)]
elb_sgs.append(sg)
# Add outputs
output_name = "ELB" + safe_name
logging.debug("config:elb:Adding output to ELB '%s'" % (output_name))
template.add_output(Output(
output_name,
Description="ELB DNSName",
Value=GetAtt(load_balancer, "DNSName")