-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathterrascript_client.py
4194 lines (3756 loc) · 170 KB
/
terrascript_client.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 base64
from dataclasses import dataclass
import enum
import json
import logging
import os
import random
import re
import string
import tempfile
from threading import Lock
from typing import (
Any, Dict, List, Iterable, Mapping, MutableMapping, Optional
)
from ipaddress import ip_network, ip_address
import anymarkup
import requests
from terrascript import (Terrascript, provider, Provider, Terraform,
Backend, Output, data)
from terrascript.resource import (
aws_db_instance, aws_db_parameter_group,
aws_s3_bucket, aws_iam_user,
aws_s3_bucket_notification,
aws_iam_access_key, aws_iam_user_policy,
aws_iam_group,
aws_iam_group_policy_attachment,
aws_iam_user_group_membership,
aws_iam_user_login_profile, aws_iam_policy,
aws_iam_role, aws_iam_role_policy,
aws_iam_role_policy_attachment,
aws_elasticache_replication_group,
aws_elasticache_parameter_group,
aws_iam_user_policy_attachment,
aws_sqs_queue, aws_dynamodb_table,
aws_ecr_repository, aws_s3_bucket_policy,
aws_cloudfront_origin_access_identity,
aws_cloudfront_distribution,
aws_vpc_peering_connection,
aws_vpc_peering_connection_accepter,
aws_ram_resource_share,
aws_ram_principal_association,
aws_ram_resource_association,
aws_ram_resource_share_accepter,
aws_ec2_transit_gateway_vpc_attachment,
aws_ec2_transit_gateway_vpc_attachment_accepter,
aws_ec2_transit_gateway_route,
aws_security_group,
aws_security_group_rule,
aws_route,
aws_cloudwatch_log_group,
aws_cloudwatch_log_resource_policy,
aws_kms_key,
aws_kms_alias,
aws_elasticsearch_domain,
aws_iam_service_linked_role,
aws_lambda_function, aws_lambda_permission,
aws_cloudwatch_log_subscription_filter,
aws_acm_certificate,
aws_kinesis_stream,
aws_route53_zone,
aws_route53_record,
aws_route53_health_check,
aws_cloudfront_public_key,
aws_lb,
aws_lb_target_group,
aws_lb_target_group_attachment,
aws_lb_listener,
aws_lb_listener_rule,
aws_secretsmanager_secret,
aws_secretsmanager_secret_version,
aws_iam_instance_profile,
aws_launch_template,
aws_autoscaling_group,
random_id,
)
# temporary to create aws_ecrpublic_repository
from terrascript import Resource
from sretoolbox.utils import threaded
from reconcile.utils import gql
from reconcile.utils.aws_api import AWSApi
from reconcile.utils.secret_reader import SecretReader
from reconcile.utils.git import is_file_in_git_repo
from reconcile.github_org import get_default_config
from reconcile.utils.gpg import gpg_key_valid
from reconcile.utils.exceptions import (FetchResourceError,
PrintToFileInGitRepositoryError)
from reconcile.utils.elasticsearch_exceptions \
import (ElasticSearchResourceNameInvalidError,
ElasticSearchResourceMissingSubnetIdError,
ElasticSearchResourceZoneAwareSubnetInvalidError)
import reconcile.openshift_resources_base as orb
GH_BASE_URL = os.environ.get('GITHUB_API', 'https://api.github.com')
LOGTOES_RELEASE = 'repos/app-sre/logs-to-elasticsearch-lambda/releases/latest'
VARIABLE_KEYS = ['region', 'availability_zone', 'parameter_group',
'enhanced_monitoring', 'replica_source',
'output_resource_db_name', 'reset_password', 'ca_cert',
'sqs_identifier', 's3_events', 'bucket_policy',
'event_notifications', 'storage_class', 'kms_encryption',
'variables', 'policies', 'user_policy',
'es_identifier', 'filter_pattern',
'specs', 'secret', 'public', 'domain',
'aws_infrastructure_access', 'cloudinit_configs', 'image']
class UnknownProviderError(Exception):
def __init__(self, msg):
super().__init__("unknown provider error: " + str(msg))
def safe_resource_id(s):
"""Sanitize a string into a valid terraform resource id"""
res = s.translate({ord(c): "_" for c in "."})
res = res.replace("*", "_star")
return res
class aws_ecrpublic_repository(Resource):
pass
# temporary until we upgrade to a terrascript release
# that supports this provider
# https://github.com/mjuenema/python-terrascript/pull/166
class time(Provider):
pass
# temporary until we upgrade to a terrascript release
# that supports this resource
# https://github.com/mjuenema/python-terrascript/pull/166
class time_sleep(Resource):
pass
class ElasticSearchLogGroupType(enum.Enum):
INDEX_SLOW_LOGS = 'INDEX_SLOW_LOGS'
SEARCH_SLOW_LOGS = 'SEARCH_SLOW_LOGS'
ES_APPLICATION_LOGS = 'ES_APPLICATION_LOGS'
@dataclass
class ElasticSearchLogGroupInfo:
account: str
account_id: str
region: str
log_group_identifier: str
class TerrascriptClient:
def __init__(self, integration, integration_prefix,
thread_pool_size, accounts, settings=None):
self.integration = integration
self.integration_prefix = integration_prefix
self.settings = settings
self.thread_pool_size = thread_pool_size
filtered_accounts = self.filter_disabled_accounts(accounts)
self.secret_reader = SecretReader(settings=settings)
self.populate_configs(filtered_accounts)
self.versions = {a['name']: a['providerVersion']
for a in filtered_accounts}
tss = {}
locks = {}
self.supported_regions = {}
for name, config in self.configs.items():
# Ref: https://github.com/mjuenema/python-terrascript#example
ts = Terrascript()
supported_regions = config['supportedDeploymentRegions']
self.supported_regions[name] = supported_regions
if supported_regions is not None:
for region in supported_regions:
ts += provider.aws(
access_key=config['aws_access_key_id'],
secret_key=config['aws_secret_access_key'],
version=self.versions.get(name),
region=region,
alias=region)
# Add default region, which will be in resourcesDefaultRegion
ts += provider.aws(
access_key=config['aws_access_key_id'],
secret_key=config['aws_secret_access_key'],
version=self.versions.get(name),
region=config['resourcesDefaultRegion'])
# the time provider can be removed if all AWS accounts
# upgrade to a provider version with this bug fix
# https://github.com/hashicorp/terraform-provider-aws/pull/20926
ts += time(
version="0.7.2"
)
ts += provider.random(
version="3.1.0"
)
ts += provider.template(
version="2.2.0"
)
b = Backend("s3",
access_key=config['aws_access_key_id'],
secret_key=config['aws_secret_access_key'],
bucket=config['bucket'],
key=config['{}_key'.format(integration)],
region=config['region'])
ts += Terraform(backend=b)
tss[name] = ts
locks[name] = Lock()
self.tss = tss
self.locks = locks
self.accounts = {a['name']: a for a in filtered_accounts}
self.uids = {a['name']: a['uid'] for a in filtered_accounts}
self.default_regions = {a['name']: a['resourcesDefaultRegion']
for a in filtered_accounts}
self.partitions = {a['name']: a.get('partition') or 'aws'
for a in filtered_accounts}
self.logtoes_zip = ''
self.logtoes_zip_lock = Lock()
def get_logtoes_zip(self, release_url):
if not self.logtoes_zip:
with self.logtoes_zip_lock:
# this may have already happened, so we check again
if not self.logtoes_zip:
self.token = get_default_config()['token']
self.logtoes_zip = \
self.download_logtoes_zip(LOGTOES_RELEASE)
if release_url == LOGTOES_RELEASE:
return self.logtoes_zip
else:
return self.download_logtoes_zip(release_url)
def download_logtoes_zip(self, release_url):
headers = {'Authorization': 'token ' + self.token}
r = requests.get(GH_BASE_URL + '/' + release_url, headers=headers)
r.raise_for_status()
data = r.json()
zip_url = data['assets'][0]['browser_download_url']
zip_file = '/tmp/LogsToElasticsearch-' + data['tag_name'] + '.zip'
if not os.path.exists(zip_file):
r = requests.get(zip_url)
r.raise_for_status()
# pylint: disable=consider-using-with
open(zip_file, 'wb').write(r.content)
return zip_file
def filter_disabled_accounts(self, accounts):
filtered_accounts = []
for account in accounts:
try:
disabled_integrations = account['disable']['integrations']
except (KeyError, TypeError):
disabled_integrations = []
integration = self.integration.replace('_', '-')
if integration not in disabled_integrations:
filtered_accounts.append(account)
return filtered_accounts
def populate_configs(self, accounts):
results = threaded.run(self.get_tf_secrets, accounts,
self.thread_pool_size)
self.configs = dict(results)
def get_tf_secrets(self, account):
account_name = account['name']
automation_token = account['automationToken']
secret = self.secret_reader.read_all(automation_token)
secret['supportedDeploymentRegions'] = \
account['supportedDeploymentRegions']
secret['resourcesDefaultRegion'] = \
account['resourcesDefaultRegion']
return (account_name, secret)
def _get_partition(self, account):
return self.partitions.get(account) or 'aws'
@staticmethod
def get_tf_iam_group(group_name):
return aws_iam_group(
group_name,
name=group_name
)
def get_tf_iam_user(self, user_name):
return aws_iam_user(
user_name,
name=user_name,
force_destroy=True,
tags={
'managed_by_integration': self.integration
}
)
def populate_iam_groups(self, roles):
groups = {}
for role in roles:
users = role['users']
if len(users) == 0:
continue
aws_groups = role['aws_groups'] or []
for aws_group in aws_groups:
group_name = aws_group['name']
group_policies = aws_group['policies']
account = aws_group['account']
account_name = account['name']
if account_name not in groups:
groups[account_name] = {}
if group_name not in groups[account_name]:
# Ref: terraform aws iam_group
tf_iam_group = self.get_tf_iam_group(group_name)
self.add_resource(account_name, tf_iam_group)
for policy in group_policies:
# Ref: terraform aws iam_group_policy_attachment
# this may change in the near future
# to include inline policies and not
# only managed policies, as it is currently
policy_arn = \
f'arn:{self._get_partition(account_name)}:' + \
f'iam::aws:policy/{policy}'
tf_iam_group_policy_attachment = \
aws_iam_group_policy_attachment(
group_name + '-' + policy.replace('/', '_'),
group=group_name,
policy_arn=policy_arn,
depends_on=self.get_dependencies(
[tf_iam_group])
)
self.add_resource(account_name,
tf_iam_group_policy_attachment)
groups[account_name][group_name] = 'Done'
return groups
@staticmethod
def _get_aws_username(user):
return user.get('aws_username') or user['org_username']
def populate_iam_users(self, roles):
for role in roles:
users = role['users']
if len(users) == 0:
continue
aws_groups = role['aws_groups'] or []
for aws_group in aws_groups:
group_name = aws_group['name']
account_name = aws_group['account']['name']
account_console_url = aws_group['account']['consoleUrl']
# we want to include the console url in the outputs
# to be used later to generate the email invitations
output_name_0_13 = '{}_console-urls__{}'.format(
self.integration_prefix, account_name
)
output_value = account_console_url
tf_output = Output(output_name_0_13, value=output_value)
self.add_resource(account_name, tf_output)
for user in users:
user_name = self._get_aws_username(user)
# Ref: terraform aws iam_user
tf_iam_user = self.get_tf_iam_user(user_name)
self.add_resource(account_name, tf_iam_user)
# Ref: terraform aws iam_group_membership
tf_iam_group = self.get_tf_iam_group(group_name)
tf_iam_user_group_membership = \
aws_iam_user_group_membership(
user_name + '-' + group_name,
user=user_name,
groups=[group_name],
depends_on=self.get_dependencies(
[tf_iam_user, tf_iam_group])
)
self.add_resource(account_name,
tf_iam_user_group_membership)
# if user does not have a gpg key,
# a password will not be created.
# a gpg key may be added at a later time,
# and a password will be generated
user_public_gpg_key = user['public_gpg_key']
if user_public_gpg_key is None:
msg = \
'user {} does not have a public gpg key ' \
'and will be created without a password.'.format(
user_name)
logging.warning(msg)
continue
try:
gpg_key_valid(user_public_gpg_key)
except ValueError as e:
msg = \
'invalid public gpg key for user {}: {}'.format(
user_name, str(e))
logging.error(msg)
error = True
return error
# Ref: terraform aws iam_user_login_profile
tf_iam_user_login_profile = aws_iam_user_login_profile(
user_name,
user=user_name,
pgp_key=user_public_gpg_key,
depends_on=self.get_dependencies([tf_iam_user]),
lifecycle={
'ignore_changes': ["id",
"password_length",
"password_reset_required",
"pgp_key"]
}
)
self.add_resource(account_name, tf_iam_user_login_profile)
# we want the outputs to be formed into a mail invitation
# for each new user. we form an output of the form
# 'qrtf.enc-passwords[user_name] = <encrypted password>
output_name_0_13 = '{}_enc-passwords__{}'.format(
self.integration_prefix, user_name)
output_value = '${' + \
tf_iam_user_login_profile.encrypted_password + '}'
tf_output = Output(output_name_0_13, value=output_value)
self.add_resource(account_name, tf_output)
user_policies = role['user_policies'] or []
for user_policy in user_policies:
policy_name = user_policy['name']
account_name = user_policy['account']['name']
account_uid = user_policy['account']['uid']
for user in users:
# replace known keys with values
user_name = self._get_aws_username(user)
policy = user_policy['policy']
policy = policy.replace('${aws:username}', user_name)
policy = \
policy.replace('${aws:accountid}', account_uid)
# Ref: terraform aws_iam_policy
tf_iam_user = self.get_tf_iam_user(user_name)
identifier = f'{user_name}-{policy_name}'
tf_aws_iam_policy = aws_iam_policy(
identifier,
name=identifier,
policy=policy,
)
self.add_resource(account_name,
tf_aws_iam_policy)
# Ref: terraform aws_iam_user_policy_attachment
tf_iam_user_policy_attachment = \
aws_iam_user_policy_attachment(
identifier,
user=user_name,
policy_arn=f"${{{tf_aws_iam_policy.arn}}}",
depends_on=self.get_dependencies(
[tf_iam_user, tf_aws_iam_policy])
)
self.add_resource(account_name,
tf_iam_user_policy_attachment)
def populate_users(self, roles):
self.populate_iam_groups(roles)
err = self.populate_iam_users(roles)
if err:
return err
@staticmethod
def get_user_id_from_arn(assume_role):
# arn:aws:iam::12345:user/id --> id
return assume_role.split('/')[1]
@staticmethod
def get_role_arn_from_role_link(role_link):
# https://signin.aws.amazon.com/switchrole?
# account=<uid>&roleName=<role_name> -->
# arn:aws:iam::12345:role/role-1
details = role_link.split('?')[1].split('&')
uid = details[0].split('=')[1]
role_name = details[1].split('=')[1]
return f"arn:aws:iam::{uid}:role/{role_name}"
@staticmethod
def get_alias_uid_from_assume_role(assume_role):
# arn:aws:iam::12345:role/role-1 --> 12345
return assume_role.split(':')[4]
def get_alias_name_from_assume_role(self, assume_role):
uid = self.get_alias_uid_from_assume_role(assume_role)
return f"account-{uid}"
def populate_additional_providers(self, accounts):
for account in accounts:
account_name = account['name']
assume_role = account['assume_role']
alias = self.get_alias_name_from_assume_role(assume_role)
ts = self.tss[account_name]
config = self.configs[account_name]
existing_provider_aliases = \
[p.get('alias') for p in ts['provider']['aws']]
if alias not in existing_provider_aliases:
ts += provider.aws(
access_key=config['aws_access_key_id'],
secret_key=config['aws_secret_access_key'],
version=self.versions.get(account_name),
region=account['assume_region'],
alias=alias,
assume_role={'role_arn': assume_role})
def populate_route53(self, desired_state, default_ttl=300):
for zone in desired_state:
acct_name = zone['account_name']
# Ensure zone is in the state for the given account
zone_id = safe_resource_id(f"{zone['name']}")
zone_values = {
'name': zone['name'],
'vpc': zone.get('vpc'),
'comment': 'Managed by Terraform'
}
zone_resource = aws_route53_zone(zone_id, **zone_values)
self.add_resource(acct_name, zone_resource)
counts = {}
for record in zone['records']:
record_fqdn = f"{record['name']}.{zone['name']}"
record_id = safe_resource_id(
f"{record_fqdn}_{record['type'].upper()}")
# Count record names so we can generate unique IDs
if record_id not in counts:
counts[record_id] = 0
counts[record_id] += 1
# If more than one record with a given name, append _{count}
if counts[record_id] > 1:
record_id = f"{record_id}_{counts[record_id]}"
# Use default TTL if none is specified
# or if this record is an alias
# None/zero is accepted but not a good default
if not record.get('alias') and record.get('ttl') is None:
record['ttl'] = default_ttl
# Define healthcheck if needed
healthcheck = record.pop('healthcheck', None)
if healthcheck:
healthcheck_id = record_id
healthcheck_values = {**healthcheck}
healthcheck_resource = aws_route53_health_check(
healthcheck_id, **healthcheck_values)
self.add_resource(acct_name, healthcheck_resource)
# Assign the healthcheck resource ID to the record
record['health_check_id'] = \
f"${{{healthcheck_resource.id}}}"
record_values = {
'zone_id': f"${{{zone_resource.id}}}",
**record
}
record_resource = aws_route53_record(record_id,
**record_values)
self.add_resource(acct_name, record_resource)
def populate_vpc_peerings(self, desired_state):
for item in desired_state:
if item['deleted']:
continue
connection_provider = item['connection_provider']
connection_name = item['connection_name']
requester = item['requester']
accepter = item['accepter']
req_account = requester['account']
req_account_name = req_account['name']
req_alias = self.get_alias_name_from_assume_role(
req_account['assume_role'])
# Requester's side of the connection - the cluster's account
identifier = f"{requester['vpc_id']}-{accepter['vpc_id']}"
values = {
# adding the alias to the provider will add this resource
# to the cluster's AWS account
'provider': 'aws.' + req_alias,
'vpc_id': requester['vpc_id'],
'peer_vpc_id': accepter['vpc_id'],
'peer_region': accepter['region'],
'peer_owner_id': req_account['uid'],
'auto_accept': False,
'tags': {
'managed_by_integration': self.integration,
# <accepter account uid>-<accepter account vpc id>
'Name': connection_name
}
}
req_peer_owner_id = requester.get('peer_owner_id')
if req_peer_owner_id:
values['peer_owner_id'] = req_peer_owner_id
tf_resource = aws_vpc_peering_connection(identifier, **values)
self.add_resource(req_account_name, tf_resource)
# add routes to existing route tables
route_table_ids = requester.get('route_table_ids')
if route_table_ids:
for route_table_id in route_table_ids:
values = {
'provider': 'aws.' + req_alias,
'route_table_id': route_table_id,
'destination_cidr_block': accepter['cidr_block'],
'vpc_peering_connection_id':
'${aws_vpc_peering_connection.' +
identifier + '.id}'
}
route_identifier = f'{identifier}-{route_table_id}'
tf_resource = aws_route(route_identifier, **values)
self.add_resource(req_account_name, tf_resource)
acc_account = accepter['account']
acc_account_name = acc_account['name']
acc_alias = self.get_alias_name_from_assume_role(
acc_account['assume_role'])
# Accepter's side of the connection.
values = {
'vpc_peering_connection_id':
'${aws_vpc_peering_connection.' + identifier + '.id}',
'auto_accept': True,
'tags': {
'managed_by_integration': self.integration,
# <requester account uid>-<requester account vpc id>
'Name': connection_name
}
}
if connection_provider in ['account-vpc', 'account-vpc-mesh']:
if self._multiregion_account(acc_account_name):
values['provider'] = 'aws.' + accepter['region']
else:
values['provider'] = 'aws.' + acc_alias
tf_resource = \
aws_vpc_peering_connection_accepter(identifier, **values)
self.add_resource(acc_account_name, tf_resource)
# add routes to existing route tables
route_table_ids = accepter.get('route_table_ids')
if route_table_ids:
for route_table_id in route_table_ids:
values = {
'route_table_id': route_table_id,
'destination_cidr_block': requester['cidr_block'],
'vpc_peering_connection_id':
'${aws_vpc_peering_connection_accepter.' +
identifier + '.id}'
}
if connection_provider in \
['account-vpc', 'account-vpc-mesh']:
if self._multiregion_account(acc_account_name):
values['provider'] = 'aws.' + accepter['region']
else:
values['provider'] = 'aws.' + acc_alias
route_identifier = f'{identifier}-{route_table_id}'
tf_resource = aws_route(route_identifier, **values)
self.add_resource(acc_account_name, tf_resource)
def populate_tgw_attachments(self, desired_state):
for item in desired_state:
if item['deleted']:
continue
connection_name = item['connection_name']
requester = item['requester']
accepter = item['accepter']
# Requester's side of the connection - the AWS account
req_account = requester['account']
req_account_name = req_account['name']
# Accepter's side of the connection - the cluster's account
acc_account = accepter['account']
acc_account_name = acc_account['name']
acc_alias = self.get_alias_name_from_assume_role(
acc_account['assume_role'])
acc_uid = self.get_alias_uid_from_assume_role(
acc_account['assume_role'])
tags = {
'managed_by_integration': self.integration,
'Name': connection_name
}
# add resource share
values = {
'name': connection_name,
'allow_external_principals': True,
'tags': tags
}
if self._multiregion_account(req_account_name):
values['provider'] = 'aws.' + requester['region']
tf_resource_share = \
aws_ram_resource_share(connection_name, **values)
self.add_resource(req_account_name, tf_resource_share)
# share with accepter aws account
values = {
'principal': acc_uid,
'resource_share_arn': '${' + tf_resource_share.arn + '}'
}
if self._multiregion_account(req_account_name):
values['provider'] = 'aws.' + requester['region']
tf_resource_association = \
aws_ram_principal_association(connection_name, **values)
self.add_resource(req_account_name, tf_resource_association)
# accept resource share from accepter aws account
values = {
'provider': 'aws.' + acc_alias,
'share_arn': '${' + tf_resource_share.arn + '}',
'depends_on': [
'aws_ram_resource_share.' + connection_name,
'aws_ram_principal_association.' + connection_name
]
}
tf_resource_share_accepter = \
aws_ram_resource_share_accepter(connection_name, **values)
self.add_resource(acc_account_name, tf_resource_share_accepter)
# until now it was standard sharing
# from this line onwards we will be adding content
# specific for the TGW attachments integration
# tgw share association
identifier = f"{requester['tgw_id']}-{accepter['vpc_id']}"
values = {
'resource_arn': requester['tgw_arn'],
'resource_share_arn': '${' + tf_resource_share.arn + '}'
}
if self._multiregion_account(req_account_name):
values['provider'] = 'aws.' + requester['region']
tf_resource_association = \
aws_ram_resource_association(identifier, **values)
self.add_resource(req_account_name, tf_resource_association)
# now that the tgw is shared to the cluster's aws account
# we can create a vpc attachment to the tgw
subnets_id_az = accepter['subnets_id_az']
subnets = self.get_az_unique_subnet_ids(subnets_id_az)
values = {
'provider': 'aws.' + acc_alias,
'subnet_ids': subnets,
'transit_gateway_id': requester['tgw_id'],
'vpc_id': accepter['vpc_id'],
'depends_on': [
'aws_ram_principal_association.' + connection_name,
'aws_ram_resource_association.' + identifier
],
'tags': tags
}
tf_resource_attachment = \
aws_ec2_transit_gateway_vpc_attachment(identifier, **values)
# we send the attachment from the cluster's aws account
self.add_resource(acc_account_name, tf_resource_attachment)
# and accept the attachment in the non cluster's aws account
values = {
'transit_gateway_attachment_id':
'${' + tf_resource_attachment.id + '}',
'tags': tags
}
if self._multiregion_account(req_account_name):
values['provider'] = 'aws.' + requester['region']
tf_resource_attachment_accepter = \
aws_ec2_transit_gateway_vpc_attachment_accepter(
identifier, **values)
self.add_resource(
req_account_name, tf_resource_attachment_accepter)
# add routes to existing route tables
route_table_ids = accepter.get('route_table_ids')
req_cidr_block = requester.get('cidr_block')
if route_table_ids and req_cidr_block:
for route_table_id in route_table_ids:
values = {
'provider': 'aws.' + acc_alias,
'route_table_id': route_table_id,
'destination_cidr_block': req_cidr_block,
'transit_gateway_id': requester['tgw_id']
}
route_identifier = f'{identifier}-{route_table_id}'
tf_resource = aws_route(route_identifier, **values)
self.add_resource(acc_account_name, tf_resource)
# add routes to peered transit gateways in the requester's
# account to achieve global routing from all regions
requester_routes = requester.get('routes')
if requester_routes:
for route in requester_routes:
route_region = route['region']
if route_region not in \
self.supported_regions[req_account_name]:
logging.warning(
f'[{req_account_name}] TGW in ' +
f'unsupported region: {route_region}')
continue
values = {
'destination_cidr_block': route['cidr_block'],
'transit_gateway_attachment_id':
route['tgw_attachment_id'],
'transit_gateway_route_table_id':
route['tgw_route_table_id'],
}
if self._multiregion_account(req_account_name):
values['provider'] = 'aws.' + route_region
route_identifier = f"{identifier}-{route['tgw_id']}"
tf_resource = aws_ec2_transit_gateway_route(
route_identifier, **values)
self.add_resource(req_account_name, tf_resource)
# add rules to security groups of VPCs which are attached
# to the transit gateway to allow traffic through the routes
requester_rules = requester.get('rules')
if requester_rules:
for rule in requester_rules:
rule_region = rule['region']
if rule_region not in \
self.supported_regions[req_account_name]:
logging.warning(
f'[{req_account_name}] TGW in ' +
f'unsupported region: {rule_region}')
continue
values = {
'type': 'ingress',
'from_port': 0,
'to_port': 0,
'protocol': 'all',
'cidr_blocks': [rule['cidr_block']],
'security_group_id': rule['security_group_id']
}
if self._multiregion_account(req_account_name):
values['provider'] = 'aws.' + rule_region
rule_identifier = f"{identifier}-{rule['vpc_id']}"
tf_resource = aws_security_group_rule(
rule_identifier, **values)
self.add_resource(req_account_name, tf_resource)
@staticmethod
def get_az_unique_subnet_ids(subnets_id_az):
""" returns a list of subnet ids which are unique per az """
results = []
azs = []
for subnet_id_az in subnets_id_az:
az = subnet_id_az['az']
if az in azs:
continue
results.append(subnet_id_az['id'])
azs.append(az)
return results
def populate_resources(self, namespaces, existing_secrets, account_name,
ocm_map=None):
self.init_populate_specs(namespaces, account_name)
for specs in self.account_resources.values():
for spec in specs:
self.populate_tf_resources(spec, existing_secrets,
ocm_map=ocm_map)
def init_populate_specs(self, namespaces, account_name):
self.account_resources = {}
for namespace_info in namespaces:
# Skip if namespace has no terraformResources
tf_resources = namespace_info.get('terraformResources')
if not tf_resources:
continue
for resource in tf_resources:
populate_spec = {'resource': resource,
'namespace_info': namespace_info}
account = resource['account']
# Skip if account_name is specified
if account_name and account != account_name:
continue
if account not in self.account_resources:
self.account_resources[account] = []
self.account_resources[account].append(populate_spec)
def populate_tf_resources(self, populate_spec, existing_secrets,
ocm_map=None):
resource = populate_spec['resource']
namespace_info = populate_spec['namespace_info']
provider = resource['provider']
if provider == 'rds':
self.populate_tf_resource_rds(resource, namespace_info,
existing_secrets)
elif provider == 's3':
self.populate_tf_resource_s3(resource, namespace_info)
elif provider == 'elasticache':
self.populate_tf_resource_elasticache(resource, namespace_info,
existing_secrets)
elif provider == 'aws-iam-service-account':
self.populate_tf_resource_service_account(resource,
namespace_info,
ocm_map=ocm_map)
elif provider == 'aws-iam-role':
self.populate_tf_resource_role(resource, namespace_info)
elif provider == 'sqs':
self.populate_tf_resource_sqs(resource, namespace_info)
elif provider == 'dynamodb':
self.populate_tf_resource_dynamodb(resource, namespace_info)
elif provider == 'ecr':
self.populate_tf_resource_ecr(resource, namespace_info)
elif provider == 's3-cloudfront':
self.populate_tf_resource_s3_cloudfront(resource, namespace_info)
elif provider == 's3-sqs':
self.populate_tf_resource_s3_sqs(resource, namespace_info)
elif provider == 'cloudwatch':
self.populate_tf_resource_cloudwatch(resource, namespace_info)
elif provider == 'kms':
self.populate_tf_resource_kms(resource, namespace_info)
elif provider == 'elasticsearch':
self.populate_tf_resource_elasticsearch(resource, namespace_info)
elif provider == 'acm':
self.populate_tf_resource_acm(resource, namespace_info)
elif provider == 'kinesis':
self.populate_tf_resource_kinesis(resource, namespace_info)
elif provider == 's3-cloudfront-public-key':
self.populate_tf_resource_s3_cloudfront_public_key(resource,
namespace_info)
elif provider == 'alb':
self.populate_tf_resource_alb(resource, namespace_info,
ocm_map=ocm_map)
elif provider == 'secrets-manager':
self.populate_tf_resource_secrets_manager(resource, namespace_info)
elif provider == 'asg':
self.populate_tf_resource_asg(resource, namespace_info)
else:
raise UnknownProviderError(provider)
def populate_tf_resource_rds(self, resource, namespace_info,
existing_secrets):
account, identifier, values, output_prefix, \
output_resource_name, annotations = \
self.init_values(resource, namespace_info)
tf_resources = []
self.init_common_outputs(tf_resources, namespace_info, output_prefix,
output_resource_name, annotations)
# we want to allow an empty name, so we
# only validate names which are not empty
if values.get('name') and not self.validate_db_name(values['name']):
raise FetchResourceError(
f"[{account}] RDS name must contain 1 to 63 letters, " +
"numbers, or underscores. RDS name must begin with a " +
"letter. Subsequent characters can be letters, " +
f"underscores, or digits (0-9): {values['name']}")
# we can't specify the availability_zone for an multi_az
# rds instance
if values.get('multi_az'):
az = values.pop('availability_zone', None)
else:
az = values.get('availability_zone', None)
provider = ''
if az is not None and self._multiregion_account(account):
# To get the provider we should use, we get the region
# and use that as an alias in the provider definition
provider = 'aws.' + self._region_from_availability_zone(az)
values['provider'] = provider
# 'deps' should contain a list of terraform resource names
# (not full objects) that must be created
# before the actual RDS instance should be created
deps = []
parameter_group = values.pop('parameter_group', None)
if parameter_group:
pg_values = self.get_values(parameter_group)
# Parameter group name is not required by terraform.
# However, our integration has it marked as required.
# If user does not provide a name, we will use the rds identifier
# as the name. This will allow us to reuse parameter group config
# for multiple RDS instances.
pg_name = pg_values.get('name', values['identifier'] + "-pg")
pg_identifier = pg_values.pop('identifier', None) or pg_name
pg_values['name'] = pg_name
pg_values['parameter'] = pg_values.pop('parameters')
if self._multiregion_account(account) and len(provider) > 0:
pg_values['provider'] = provider
pg_tf_resource = \
aws_db_parameter_group(pg_identifier, **pg_values)
tf_resources.append(pg_tf_resource)
deps = self.get_dependencies([pg_tf_resource])
values['parameter_group_name'] = pg_name
enhanced_monitoring = values.pop('enhanced_monitoring', None)
# monitoring interval should only be set if enhanced monitoring
# is true
if (