This repository has been archived by the owner on Nov 27, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
/
cfnpipeline.py
1680 lines (1540 loc) · 83 KB
/
cfnpipeline.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 botocore
from cStringIO import StringIO
from datetime import datetime
from functools import partial
from hashlib import sha256
import json
from multiprocessing.dummy import Pool as ThreadPool
import os
import random
import re
import shutil
import string
import time
from urllib2 import Request
from urllib2 import urlopen
import uuid
import yaml
from zipfile import ZipFile
class CFNPipeline(object):
"""Helper class for working with AWS CloudFormation templates and stacks in AWS CodePipeline."""
def __init__(self, logger, clients):
"""Initializes several variables, many are set in the consume_event method.
Args:
logger (obj): provide a logging object to use
clients (obj): provide an instance of AwsClients to use for fetching boto3 clients
"""
self.logger = logger
self.clients = clients
self.job_id = None
self.original_job_id = None
self.job_data = None
self.artifacts = None
self.user_params = None
self.output_artifacts = None
self.ci_test_path = None
self.continuation_data = None
self.continuation_event = False
self.ci_configs = None
self.stack_statuses = {
"failed": [
'CREATE_FAILED', 'ROLLBACK_FAILED', 'ROLLBACK_COMPLETE', 'DELETE_FAILED',
'UPDATE_ROLLBACK_FAILED', 'UPDATE_ROLLBACK_COMPLETE'
],
"inprogress": [
'CREATE_IN_PROGRESS', 'REVIEW_IN_PROGRESS', 'ROLLBACK_IN_PROGRESS', 'DELETE_IN_PROGRESS',
'UPDATE_IN_PROGRESS', 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS', 'UPDATE_ROLLBACK_IN_PROGRESS',
'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS'
],
"complete": ['CREATE_COMPLETE', 'DELETE_COMPLETE', 'UPDATE_COMPLETE']
}
self.event_statuses = {
"failed": ['CREATE_FAILED', 'DELETE_FAILED', 'UPDATE_FAILED'],
"inprogress": ['CREATE_IN_PROGRESS', 'DELETE_IN_PROGRESS', 'UPDATE_IN_PROGRESS'],
"complete": ['CREATE_COMPLETE', 'DELETE_COMPLETE', 'DELETE_SKIPPED', 'UPDATE_COMPLETE']
}
self.ignore_event_failure_reasons = ['Resource creation cancelled']
self.region = os.environ['AWS_DEFAULT_REGION']
self.codepipeline_client = self.clients.get('codepipeline')
self.pipeline_context = None
self.pipeline_name = None
self.stage_name = None
self.pipeline_action = None
self.pipeline_state = None
self.pipeline_execution_id = None
self.artifact_revision_data = None
self.artifact_revision_id = None
self.artifact_type = None
self.report_s3_bucket = None
self.report_s3_prefix = ''
self.report_sns_topic = None
self.report_sns_region = None
self.uuid_ns = uuid.UUID('{550eda57-0a18-4dd4-9876-c340f2d77dc7}')
self.anon_usage_reporting_url = 'https://oszclq8tyh.execute-api.us-east-1.amazonaws.com/prod/generic'
return
def put_job_success(self, message):
"""Sends a success response for this action's job id to AWS CodePipeline.
Args:
message (str): informational message to include in response
"""
self.logger.info({'event': 'return_success'})
self.anon_reporting(message, 'action_success')
self.codepipeline_client.put_job_success_result(jobId=self.job_id)
def put_job_failure(self, message):
"""Sends a failure response for this action's job id to AWS CodePipeline.
Args:
message (str): informational error message to include in response
"""
self.logger.info({'event': 'return_failure'})
self.logger.error(message)
self.anon_reporting(message, 'action_failure')
if len(message) > 265:
message = message[0:211] + '... For full details see CloudWatch logs.'
self.codepipeline_client.put_job_failure_result(
jobId=self.job_id,
failureDetails={'message': message, 'type': 'JobFailed'}
)
def continue_job_later(self, message):
"""Sends a continuation response for this action's job id to AWS CodePipeline.
Results in AWS CodePipeline re-firing this event later, including a continuation token.
The continuation-token is a json blob containing the message and original job_id.
The message can contain json if there is state data to be passed to subsequent executions
Args:
message (str): informational message to include in response
"""
self.logger.info({'event': 'return_continue'})
continuation_token = json.dumps({'job_id': self.original_job_id, 'message': message})
if len(continuation_token) > 2048:
continuation_token = json.dumps({
'job_id': self.original_job_id,
's3': self._put_continuation_data(message)
})
self.codepipeline_client.put_job_success_result(
jobId=self.job_id,
continuationToken=continuation_token
)
def anon_reporting(self, message, status):
"""Sends anonymous usage report data to AWS.
Sends anonymous data about pipeline actions. Can be opted out by setting the usage reporting
parameter in the AWS CloudFormation stack, or manually by setting the SEND_ANONYMOUS_DATA
AWS Lambda environment variable to 'No'.
Args:
message (str): informational message to include in response
status (str): type of message, eg.: "action_failure" or "action_success"
"""
try:
if self.enable_anon_usage_reporting != 'Yes':
return
time_stamp = str(datetime.utcnow().isoformat())
try:
json.dumps(message)
except Exception:
self.logging.debug("anon_reporting: Failed to dump message to json", exc_info=1)
message = str(message)
message = {
"region": self.region,
"stage_name": self.stage_name,
"pipeline_action": self.pipeline_action,
"artifact_type": self.artifact_type,
"pipeline_hash": sha256(self.pipeline_name).hexdigest(),
"execution_hash": sha256(self.pipeline_execution_id).hexdigest(),
"revision_hash": sha256(self.artifact_revision_id).hexdigest(),
"status": status,
"message": message
}
postDict = {
'Data': message,
'TimeStamp': time_stamp,
'Solution': 'SO0025a',
'UUID': self.anon_usage_reporting_uuid
}
headers = {'content-type': 'application/json'}
req = Request(self.anon_usage_reporting_url, json.dumps(postDict), headers)
rsp = urlopen(req)
content = rsp.read()
rspcode = rsp.getcode()
self.logger.debug('Response Code: {}'.format(rspcode))
self.logger.debug('Response Content: {}'.format(content))
except Exception:
self.logger.debug("anon_reporting: Failed to report usage", exc_info=1)
return
def _put_continuation_data(self, message):
self.logger.debug("Putting continuationToken message on s3...")
s3_client = self.clients.get('s3')
bucket = self.user_params['ScratchBucket']
key = "continuationTokens/%s" % self.original_job_id
s3_client.put_object(Bucket=bucket, Key=key, Body=StringIO(json.dumps(message)).read())
return {'bucket': bucket, 'key': key}
def _fetch_continuation_data(self):
self.logger.debug("Getting continuationToken...")
token = json.loads(self.job_data['continuationToken'])
self.original_job_id = token['job_id']
if "s3" in token.keys():
self.logger.debug("Getting continuationToken message from s3...")
s3_client = self.clients.get('s3')
body = s3_client.get_object(
Bucket=token['s3']['bucket'],
Key=token['s3']['key']
)['Body']
message = json.loads(body.read())
token['message'] = message
token.pop('s3')
return token
def consume_event(self, event, context, loglevel='info'):
"""Handles the input event AWS Lambda receives from AWS CodePipeline.
Fetches several variables from the event for re-use in the class.
Gets information about the running action in AWS CodePipeline (name,stage,executionid, etc).
Configures the logger to add several ids to the log format
fetches artifacts from s3 and parses the ci config files
Args:
event (dict): lambda event
context (obj): lambda context
loglevel (str): optionally set log verbosity
"""
self.logger.debug("Split event into usable pieces...")
self.job_id = event['CodePipeline.job']['id']
self.job_data = event['CodePipeline.job']['data']
if 'continuationToken' not in self.job_data:
self.original_job_id = self.job_id
else:
self.continuation_data = self._fetch_continuation_data()
self.logger.config(context.aws_request_id, job_id=self.job_id, original_job_id=self.original_job_id,
loglevel=loglevel)
cp = self.clients.get('codepipeline')
response = cp.get_job_details(jobId=self.job_id)
self.logger.debug({"api": "get_job_details", "response": response})
self.pipeline_context = response['jobDetails']['data']['pipelineContext']
self.pipeline_name = self.pipeline_context['pipelineName']
self.stage_name = self.pipeline_context['stage']['name']
self.pipeline_action = self.pipeline_context['action']['name']
response = cp.get_pipeline_state(name=self.pipeline_name)
self.logger.debug({"api": "get_pipeline_state", "response": response})
self.pipeline_state = response
for stage in self.pipeline_state['stageStates']:
if stage['stageName'] == self.stage_name:
self.pipeline_execution_id = stage['latestExecution']['pipelineExecutionId']
response = cp.get_pipeline_execution(pipelineName=self.pipeline_name,
pipelineExecutionId=self.pipeline_execution_id)
self.logger.debug({"api": "get_pipeline_execution", "response": response})
self.artifact_revision_data = response['pipelineExecution']['artifactRevisions'][0]
self.artifact_revision_id = self.artifact_revision_data['revisionId']
self.logger.config(context.aws_request_id, job_id=self.original_job_id, original_job_id=self.job_id,
pipeline_execution_id=self.pipeline_execution_id, stage_name=self.stage_name,
pipeline_action=self.pipeline_action, pipeline_name=self.pipeline_name,
artifact_revision_id=self.artifact_revision_id, loglevel=loglevel)
self.artifacts = self.job_data['inputArtifacts']
self.output_artifacts = self.job_data['outputArtifacts']
try:
self.user_params = json.loads(
self.job_data['actionConfiguration']['configuration']['UserParameters'])
except Exception as e:
self.logger.error("Failed to parse user parameters", exc_info=1)
msg = "Failed to parse user parameters (\"%s\") %s"
self.put_job_failure(msg % (
self.job_data['actionConfiguration']['configuration']['UserParameters'], str(e)))
raise ValueError(msg % (
self.job_data['actionConfiguration']['configuration']['UserParameters'], str(e)))
if "CITestPath" not in self.user_params.keys():
self.put_job_failure("CITestPath missing from user parameters, cannot continue...")
self.logger.error("CITestPath missing from user parameters, cannot continue...")
raise ValueError("CITestPath missing from user parameters, cannot continue...")
if "CleanupNonFailed" in self.user_params:
if self.user_params["CleanupNonFailed"] == 'No':
self.cleanup_non_failed = False
else:
self.cleanup_non_failed = True
if "CleanupFailed" in self.user_params:
if self.user_params["CleanupFailed"] == 'Yes':
self.cleanup_failed = True
else:
self.cleanup_failed = False
if "CleanupPrevious" in self.user_params:
if self.user_params["CleanupPrevious"] == 'No':
self.cleanup_previous = False
else:
self.cleanup_previous = True
if 'continuationToken' not in self.job_data:
self.logger.debug("This is a new pipeline run...")
self.continuation_event = False
self.continuation_data = None
self._fetch_artifact()
self.ci_configs = self._get_ci_configs()
else:
self.logger.debug("This is a continuation event...")
self.continuation_event = True
self.ci_configs = self.continuation_data['message']['configs']
if 'ReportBucket' in self.user_params:
self.report_s3_bucket = self.user_params['ReportBucket']
if 'ReportKey' in self.user_params:
self.report_s3_prefix = self.user_params['ReportKey']
if 'SNSTopic' in self.user_params:
self.report_sns_topic = self.user_params['SNSTopic']
self.report_sns_region = self.report_sns_topic.split(':')[3]
try:
self.enable_anon_usage_reporting = os.environ['SEND_ANONYMOUS_DATA']
except Exception:
self.enable_anon_usage_reporting = 'Yes'
try:
sts_client = self.clients.get('sts')
self.account_id = sts_client.get_caller_identity()['Account']
pl_ns = "%s:%s:%s" % (self.account_id, self.region, self.pipeline_name)
self.anon_usage_reporting_uuid = str(uuid.uuid5(self.uuid_ns, pl_ns))
except Exception:
self.anon_usage_reporting_uuid = str(self.uuid_ns)
return
def _fetch_artifact(self):
"""Fetches input artifact from S3 and unzips it in /tmp/artifacts/"""
s3_client = self.clients.get(
's3',
region=None,
access_key=self.job_data['artifactCredentials']['accessKeyId'],
secret_key=self.job_data['artifactCredentials']['secretAccessKey'],
session_token=self.job_data['artifactCredentials']['sessionToken'],
s3v4=True
)
a = self.artifacts[0]
a_path = '/tmp/artifacts/%s' % (self.pipeline_name)
try:
shutil.rmtree(a_path)
except Exception:
pass
os.makedirs(a_path)
bucket = a['location']['s3Location']['bucketName']
key = a['location']['s3Location']['objectKey']
self.logger.debug(bucket)
self.logger.debug(key)
response = s3_client.get_object(Bucket=bucket, Key=key)
f = open('/tmp/artifact.zip', 'wb')
f.write(response['Body'].read())
f.close()
ZipFile('/tmp/artifact.zip').extractall('%s/%s' % (a_path, a['name']))
os.remove('/tmp/artifact.zip')
self.logger.debug("Fetched artifacts from s3...")
paths = []
for root, dirs, files in os.walk(a_path):
paths.append([root, dirs, files])
self.logger.debug({"event": "artifact_contents", "files": [root, dirs, files]})
self.artifact_type = 'template'
if len(paths) == 2:
if paths[1][1] == [] and paths[1][2] == ["artifact.json"]:
self.artifact_type = 'stack'
return
def _get_ci_configs(self):
"""parses ci config yaml files.
returns a dict containing lists of parsed contents of each config file
in each artifact (only 1 artifact supported at present).
Config file can contain any valid yaml, but must contain at least one test
that specifies at least parameter_input and template_file, for example:
If artifact contains a template repo, then config is fetched from all .yml
files in /ci/ folder.
If there are duplicate keys defined in different config files they are
overwritten in alphabetical filename order::
tests:
defaults:
parameter_input: aws-vpc-defaults.json
template_file: aws-vpc.template
Returns:
dict: key is config file name, value is the yaml contents converted to a python dict
"""
a = self.artifacts[0]["name"]
if self.artifact_type == 'template':
configs = {}
configs[a] = []
log_msg = "getting configs from /tmp/artifacts/%s/%s/%s" % (
self.pipeline_name, a, self.user_params["CITestPath"])
self.logger.debug(log_msg)
for root, dirs, files in os.walk("/tmp/artifacts/%s/%s/%s" % (
self.pipeline_name, a, self.user_params["CITestPath"])):
self.logger.debug({"event": "configs_contents", "files": [root, dirs, files]})
for file in files:
if file.endswith(".yml"):
with open(os.path.join(root, file), 'r') as stream:
configs[a].append(yaml.load(stream))
elif self.artifact_type == 'stack':
with open("/tmp/artifacts/%s/%s/artifact.json" % (self.pipeline_name, a), 'r') as stream:
configs = json.load(stream)
for s in configs["Stacks"]:
for a in configs["Configs"][s['artifact']]:
if s['testname'] in a["tests"].keys():
if 'built_stacks' not in a["tests"][s['testname']].keys():
a["tests"][s['testname']]['built_stacks'] = {}
if s['region'] not in a["tests"][s['testname']]['built_stacks'].keys():
a["tests"][s['testname']]['built_stacks'][s['region']] = []
a["tests"][s['testname']]['built_stacks'][s['region']].append(s['stackid'])
configs = configs["Configs"]
return configs
def _check_stack_status(self, stack):
"""checks the status of a particular stack
Args:
stack (dict): contains region and stackid keys describing a cloudformation stack
"""
try:
self.logger.debug('check_stack_status: %s' % stack)
region = stack['region']
stack_id = stack['stackid']
cfn = self.clients.get('cloudformation', region)
self.logger.debug("Checking stack status %s in %s" % (stack_id, region))
s = cfn.describe_stacks(StackName=stack_id)['Stacks'][0]
artifact, testname = None, None
for tag in s['Tags']:
if tag['Key'] == 'cfn_cicd_artifact':
artifact = tag['Value']
if tag['Key'] == 'cfn_cicd_testname':
testname = tag['Value']
if s['StackStatus'] in self.stack_statuses["failed"]:
stack_events = cfn.describe_stack_events(StackName=s['StackId'])['StackEvents']
error_events = []
for e in stack_events:
is_failed = e['ResourceStatus'] in self.event_statuses['failed']
if 'ResourceStatusReason' in e:
dont_ignore = e['ResourceStatusReason'] not in self.ignore_event_failure_reasons
else:
dont_ignore = True
if is_failed and dont_ignore:
error_events.append(
[e['ResourceStatus'], e['LogicalResourceId'], e['ResourceStatusReason']]
)
try:
state = [s['StackStatus'], s['StackStatusReason'], error_events]
except Exception:
try:
state = [s['StackStatus'], error_events]
except Exception:
state = [s['StackStatus']]
results = {'status': 'error', 'detail': state}
elif s['StackStatus'] in self.stack_statuses["inprogress"]:
results = {'status': 'inprogress', 'detail': s['StackStatus']}
elif s['StackStatus'] in self.stack_statuses["complete"]:
results = {'status': 'success', 'detail': s['StackStatus']}
else:
raise NameError("Encountered unsupported StackStatus %s" % s['StackStatus'])
if artifact and testname:
results.update({'artifact': artifact, 'testname': testname})
results.update({'stackid': s['StackId'], 'region': region})
return results
except Exception:
self.logger.error("_check_stack_status failed", exc_info=1)
raise
def check_statuses(self, stacks):
"""Checks status of a list of stacks
Args:
stacks (list): a list containing dicts describing AWS CloudFormation stacks (region and stackid)
"""
successes = []
errors = []
inprogress = []
regions = []
for s in stacks:
if s['region'] not in regions:
regions.append(s['region'])
if len(regions) > 0:
self.logger.debug("check_statuses: %s" % stacks)
pool = ThreadPool(len(regions))
results = pool.map(self._check_stack_status, stacks)
pool.close()
pool.join()
for r in results:
if r['status'] == 'success':
successes.append(r)
elif r['status'] == 'inprogress':
inprogress.append(r)
else:
errors.append(r)
self.logger.debug("stack statuses: %s " % [successes, inprogress, errors])
return {"success": successes, "inprogress": inprogress, "error": errors}
def cleanup_previous_stacks(self):
"""Deletes stacks from previous pipeline runs
Returns:
list: AWS CloudFormation stackids
"""
stacks = []
self.logger.debug("configs: %s" % str(self.ci_configs))
for artifact in self.ci_configs.keys():
for config in self.ci_configs[artifact]:
self.logger.debug("config: %s" % str(config))
for testname in config['tests']:
self.logger.debug("testname: %s" % str(testname))
test = config['tests'][testname]
self.logger.debug("test %s" % str(test))
regions = self._build_regions(config, test)
self.logger.debug("regions %s" % str(regions))
pool = ThreadPool(len(regions))
func = partial(self._get_previous, artifact=artifact, testname=testname)
results = pool.map(func, regions)
pool.close()
pool.join()
self.logger.debug("Stacks to add to delete list: %s" % results)
for r in results:
stacks += r
self.logger.debug("Deleting Stacks: %s" % str(stacks))
return self.delete_stacks(stacks)
def _get_previous(self, r, artifact, testname):
"""gets a list of stacks that are not deleted and associated with previous pipeline runs.
Args:
r (str): region
artifact (str): artifact name
testname (str): name of test as defined in the ci config file
"""
stacks = []
cfn = self.clients.get('cloudformation', r)
response = cfn.describe_stacks()
for s in response['Stacks']:
self.logger.debug("stack: %s" % str(s))
tags = {t['Key']: t['Value'] for t in s['Tags']}
if set(["cfn_cicd_artifact", "cfn_cicd_jobid", "cfn_cicd_testname"]).issubset(tags.keys()):
if tags["cfn_cicd_artifact"] == artifact and testname == tags["cfn_cicd_testname"] and tags['cfn_cicd_pipeline'] == self.pipeline_name:
stacks.append({'artifact': artifact, 'testname': testname, 'region': r,
'stackid': s['StackId']})
return stacks
def delete_provisioned_product(self, provisioned_product_id, stack_id, region):
"""Deletes a particular provisioned product and all the other related AWS Service Catalog artifacts.
Args:
Provisioned product (str): provisioned_product_id for provisioned product to be deleted
"""
sc = self.clients.get('servicecatalog', region)
cfn = self.clients.get('cloudformation', region)
try:
self.logger.debug("Deleting provisioned product %s in %s" % (provisioned_product_id, region))
response = sc.scan_provisioned_products(AccessLevelFilter={'Key': 'Account', 'Value': 'self'})
while 'PageToken' in response:
for item in response['ProvisionedProducts']:
if item['Id'] == provisioned_product_id:
record_id = item['LastRecordId']
response = sc.scan_provisioned_products(AccessLevelFilter={'Key': 'Account', 'Value': 'self'},
PageSize=1,
PageToken=response['PageToken']
)
for item in response['ProvisionedProducts']:
if item['Id'] == provisioned_product_id:
record_id = item['LastRecordId']
response = sc.describe_record(Id=record_id)
product_id = response['RecordDetail']['ProductId']
try:
response = sc.terminate_provisioned_product(ProvisionedProductId=provisioned_product_id, TerminateToken=str(uuid.uuid4()))
self.logger.debug("Provisioned product %s terminated" % provisioned_product_id)
except Exception as e:
self.logger.error("Failed to terminate provisioned product %s. Falling back to deleting the CloudFormation stack instead" % (provisioned_product_id), exc_info=1)
try:
self.logger.debug("Deleting stack %s in %s" % (stack_id, region))
cfn.delete_stack(StackName=stack_id)
except Exception as e:
self.logger.error("Failed to delete stack %s in %s" % (stack_id, region), exc_info=1)
raise e
response = sc.list_portfolios_for_product(ProductId=product_id)
portfolio_id = response['PortfolioDetails'][0]['Id']
response = sc.list_principals_for_portfolio(PortfolioId=portfolio_id)
principal_arn = response['Principals'][0]['PrincipalARN']
response = sc.disassociate_principal_from_portfolio(PortfolioId=portfolio_id, PrincipalARN=principal_arn)
self.logger.debug("Principal %s disassociated from portfolio %s" % (principal_arn, portfolio_id))
response = sc.list_constraints_for_portfolio(PortfolioId=portfolio_id)
constraint_id = response['ConstraintDetails'][0]['ConstraintId']
response = sc.delete_constraint(Id=constraint_id)
self.logger.debug("Constraint %s deleted from portfolio %s" % (constraint_id, portfolio_id))
response = sc.disassociate_product_from_portfolio(ProductId=product_id, PortfolioId=portfolio_id)
self.logger.debug("Product %s disassociated from portfolio %s" % (product_id, portfolio_id))
response = sc.delete_product(Id=product_id)
self.logger.debug("Product %s deleted from %s" % (product_id, region))
response = sc.delete_portfolio(Id=portfolio_id)
self.logger.debug("Portfolio %s deleted from %s" % (portfolio_id, region))
return {'status': "success", 'stackid': stack_id, 'region': region, 'detail': None}
except Exception as e:
self.logger.error("Failed to delete provisioned product %s with stack %s in %s" % (provisioned_product_id,
stack_id,
region), exc_info=1)
return {'status': "error", 'stackid': stack_id, 'region': region, 'detail': str(e)}
def _delete_stack(self, stack):
"""Deletes a particular stack.
Args:
stack (str): stackid (arn) for stack to be deleted
"""
self.logger.debug('delete_stack: %s' % stack)
region = stack['region']
stack_id = stack['stackid']
# Check for Service Catalog stacks
match = re.search(r'(pp-)\w+', stack_id)
if match is not None:
self.logger.debug('Service Catalog product detected: %s with provisioned product id %s' % (stack, match.group()))
return self.delete_provisioned_product(match.group(), stack_id, region)
else:
cfn = self.clients.get('cloudformation', region)
try:
self.logger.debug("Deleting stack %s in %s" % (stack_id, region))
cfn.delete_stack(StackName=stack_id)
return {'status': "success", 'stackid': stack_id, 'region': region, 'detail': None}
except Exception as e:
self.logger.error("Failed to delete stack %s in %s" % (stack_id, region), exc_info=1)
return {'status': "error", 'stackid': stack_id, 'region': region, 'detail': str(e)}
def delete_stacks(self, stacks):
"""Deletes one or more AWS CloudFormation stacks.
Args:
stacks (list): a list containing dicts describing AWS CloudFormation stacks (region and stackid)
Returns:
dict: contains one or more of "success", "inprogress" or "error" keys, each containing a list of stackids
"""
successes = []
errors = []
regions = []
for s in stacks:
if s['region'] not in regions:
regions.append(s['region'])
if len(regions) > 0:
pool = ThreadPool(len(regions))
results = pool.map(self._delete_stack, stacks)
pool.close()
pool.join()
for r in results:
if r['status'] == 'success':
successes.append(r)
else:
errors.append(r)
if len(errors) > 0:
return {"success": successes, "inprogress": [], "error": errors}
return self.check_statuses(successes)
def _create_stack(self, region, artifact, testname, template_url, parameter_input,
role_arn, key_bucket, disable_rollback=True):
"""creates a CloudFormation stack.
Args:
region (str): region name
artifact (str): artifact name
testname (str): ci test name from config yaml file
template_url (str): s3 url to template
parameter_input (list): a list of parameter key value pairs
role_arn (str): role to launch stack with
key_bucket (str): bucket to store keypairs in
disable_rollback (bool): [optional] specify whether to disable rollback on failure, defaults to True
"""
self.logger.debug("creating stacks for artifact: %s, testname: %s, region: %s" % (
artifact, testname, region))
cfn = self.clients.get('cloudformation', region)
stack_name = 'ci-' + testname + '-' + self._random_string(8)
self._create_keypair(stack_name, key_bucket, region)
self.logger.debug("parameter_input pre: %s" % parameter_input)
rendered_params = self._render_param_variables(parameter_input, region, stack_name)
self.logger.debug("parameter_input rendered_params: %s" % rendered_params)
try:
response = cfn.create_stack(
StackName=stack_name,
TemplateURL=template_url,
Parameters=rendered_params,
RoleARN=role_arn,
DisableRollback=disable_rollback,
Capabilities=[
'CAPABILITY_IAM',
'CAPABILITY_NAMED_IAM'
],
Tags=[
{
'Key': 'cfn_cicd_artifact',
'Value': artifact
},
{
'Key': 'cfn_cicd_jobid',
'Value': self.job_id
},
{
'Key': 'cfn_cicd_executionid',
'Value': self.pipeline_execution_id
},
{
'Key': 'cfn_cicd_testname',
'Value': testname
},
{
'Key': 'cfn_cicd_pipeline',
'Value': self.pipeline_name
}
]
)
return {'status': 'success', 'stackid': response['StackId'], 'region': region,
'detail': None, 'artifact': artifact, 'testname': testname}
# return [None, response['StackId'], region]
except Exception as e:
self.logger.error("CreateStack Failed", exc_info=1)
try:
stackid = response['StackId']
except Exception:
stackid = None
return {'status': 'error', 'stackid': stackid, 'region': region,
'detail': str(e), 'artifact': artifact, 'testname': testname}
def create_stacks(self):
"""Creates all AWS CloudFormation stacks defined by the ci config
Returns:
dict: contains one or more of "success" or "error" keys, each containing a list of stackids
"""
errors = []
successes = []
for artifact in self.ci_configs.keys():
for config in self.ci_configs[artifact]:
for testname in config['tests']:
test = config['tests'][testname]
regions = self._build_regions(config, test)
template_url = self.upload_template(
artifact, test['template_file'], self.user_params['ScratchBucket'],
self.region
)
self.logger.debug("template_url: %s" % template_url)
try:
self.logger.debug("parameter_input: %s" % test['parameter_input'])
parameter_input = self._get_parameter_input(artifact, test['parameter_input'])
pool = ThreadPool(len(regions))
func = partial(
self._create_stack, artifact=artifact, testname=testname,
template_url=template_url, parameter_input=parameter_input,
role_arn=self.user_params['StackCreationRoleArn'],
key_bucket=self.user_params['KeyBucket']
)
results = pool.map(func, regions)
pool.close()
pool.join()
for result in results:
if result['status'] == 'error':
errors.append(result)
else:
successes.append(result)
except Exception:
self.logger.error("Stack creation failed for artifact %s testname %s" % (
artifact, testname), exc_info=1)
raise
self.logger.debug("Created Stacks: %s" % str([errors, successes]))
results = self.check_statuses(successes)
results["error"] += errors
return results
def _provision_product(self, region, artifact, testname, template_url, parameter_input,
role_arn, key_bucket, disable_rollback=True):
"""publishes a service catalog product.
Args:
region (str): region name
artifact (str): artifact name
testname (str): ci test name from config yaml file
template_url (str): s3 url to template
parameter_input (list): a list of parameter key value pairs
role_arn (str): role to launch stack with
key_bucket (str): bucket to store keypairs in
disable_rollback (bool): [optional] specify whether to disable rollback on failure, defaults to True
"""
self.logger.debug("publishing products for artifact: %s, testname: %s, region: %s" % (
artifact, testname, region))
sc = self.clients.get('servicecatalog', region)
cfn = self.clients.get('cloudformation', region)
product_name = 'ci-' + testname + '-' + self._random_string(8)
self._create_keypair(product_name, key_bucket, region)
self.logger.debug("parameter_input pre: %s" % parameter_input)
rendered_params = self._render_param_variables(parameter_input, region, product_name)
for parm in rendered_params:
parm['Value'] = parm.pop('ParameterValue')
parm['Key'] = parm.pop('ParameterKey')
self.logger.debug("parameter_input rendered_params: %s" % rendered_params)
token = str(uuid.uuid4())
try:
response = sc.create_portfolio(DisplayName="PipelineTestPortfolio" + self._random_string(8),
Description="An ephemeral test portfolio for the use of testing product\
publishing",
IdempotencyToken=token, ProviderName="pipeline_ops")
portfolio_id = response['PortfolioDetail']['Id']
self.logger.debug("Portfolio %s created in %s" % (portfolio_id, region))
response = sc.create_product(Name=product_name, Owner='Pipeline_Ops',
ProductType='CLOUD_FORMATION_TEMPLATE',
ProvisioningArtifactParameters={
'Name': 'v1',
'Description': 'test version 1',
'Info': {
'LoadTemplateFromURL': template_url
},
'Type': 'CLOUD_FORMATION_TEMPLATE'
},
IdempotencyToken=token
)
product_id = response['ProductViewDetail']['ProductViewSummary']['ProductId']
self.logger.debug("Product %s created in %s" % (product_id, region))
execution_role = os.environ['execution_role']
provisioning_artifact_id = response['ProvisioningArtifactDetail']['Id']
response = sc.associate_product_with_portfolio(PortfolioId=portfolio_id, ProductId=product_id)
self.logger.debug("Product %s associated with portfolio %s" % (product_id, portfolio_id))
response = sc.associate_principal_with_portfolio(PortfolioId=portfolio_id, PrincipalARN=execution_role,
PrincipalType='IAM')
self.logger.debug("Principal %s associated with portfolio %s" % (execution_role, portfolio_id))
launch_constraint_parameter = '{\"RoleArn\":\"' + role_arn + '\"}'
response = sc.create_constraint(Description="Launch role constraint",
IdempotencyToken=token,
Parameters=launch_constraint_parameter,
PortfolioId=portfolio_id,
ProductId=product_id,
Type="LAUNCH")
constraint_id = response['ConstraintDetail']['ConstraintId']
self.logger.debug("Constraint %s added to product %s in portfolio %s" % (constraint_id, product_id, portfolio_id))
while True:
try:
response = sc.provision_product(ProductId=product_id,
ProvisioningArtifactId=provisioning_artifact_id,
ProvisionedProductName=product_name,
ProvisioningParameters=rendered_params,
ProvisionToken=token,
Tags=[
{
'Key': 'cfn_cicd_artifact',
'Value': artifact
},
{
'Key': 'cfn_cicd_jobid',
'Value': self.job_id
},
{
'Key': 'cfn_cicd_executionid',
'Value': self.pipeline_execution_id
},
{
'Key': 'cfn_cicd_testname',
'Value': testname
},
{
'Key': 'cfn_cicd_pipeline',
'Value': self.pipeline_name
}
]
)
provisioned_product_id = response['RecordDetail']['ProvisionedProductId']
self.logger.debug(response)
self.logger.debug("Product %s in the %s region, has been provisioned as %s from portfolio %s" % (product_id,
region,
provisioned_product_id,
portfolio_id))
break
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'ResourceNotFoundException':
self.logger.error('Product not ready yet. Retrying in 5 seconds...', exc_info=1)
time.sleep(5)
else:
self.logger.error(e)
raise
# Following section is to use the provisoned product id to get the stack ID and return it to the pipeline
filters = ['CREATE_IN_PROGRESS',
'CREATE_FAILED', 'CREATE_COMPLETE',
'ROLLBACK_IN_PROGRESS', 'ROLLBACK_FAILED',
'ROLLBACK_COMPLETE', 'DELETE_IN_PROGRESS',
'DELETE_FAILED', 'UPDATE_IN_PROGRESS',
'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS',
'UPDATE_COMPLETE', 'UPDATE_ROLLBACK_IN_PROGRESS',
'UPDATE_ROLLBACK_FAILED',
'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS',
'UPDATE_ROLLBACK_COMPLETE', 'REVIEW_IN_PROGRESS']
found = False
response = sc.scan_provisioned_products(AccessLevelFilter={'Key': 'Account', 'Value': 'self'})
while 'PageToken' in response:
for item in response['ProvisionedProducts']:
if item['Id'] == provisioned_product_id:
self.logger.debug('Provisioned product status: ' + item['Status'])
response = sc.scan_provisioned_products(AccessLevelFilter={'Key': 'Account', 'Value': 'self'},
PageSize=1,
PageToken=response['PageToken']
)
for item in response['ProvisionedProducts']:
if item['Id'] == provisioned_product_id:
self.logger.debug('Provisioned product status: ' + item['Status'])
self.logger.debug('Starting search for: ' + provisioned_product_id)
count = 0
while found is False:
count += 1
if count == 5:
try:
response = sc.terminate_provisioned_product(ProvisionedProductId=provisioned_product_id, TerminateToken=str(uuid.uuid4()))
self.logger.debug("Stack not found, provisioned product %s terminated" % provisioned_product_id)
except Exception as e:
self.logger.error('Unable to terminate the failed provision product: ', exc_info=1)
raise Exception('Stack not found using provisioned product ID.')
time.sleep(3)
response_stack = cfn.list_stacks(StackStatusFilter=filters)
stacks = []
while 'NextToken' in response_stack:
for stack_summary in response_stack['StackSummaries']:
stacks.append(stack_summary['StackId'])
response_stack = cfn.list_stacks(NextToken=response_stack['NextToken'], StackStatusFilter=filters)
for stack_summary in response_stack['StackSummaries']:
stacks.append(stack_summary['StackId'])
for stack in stacks:
match = re.search(r'(pp-)\w+', stack)
if match is not None:
provisioned_stack_id = stack
found_provisioned_product_id = match.group()
if provisioned_product_id == found_provisioned_product_id:
found = True
self.logger.debug("Stack %s has been found using the provisioned product ID %s" % (provisioned_stack_id, provisioned_product_id))
break
return {'status': 'success', 'stackid': provisioned_stack_id, 'region': region,
'detail': None, 'artifact': artifact, 'testname': testname}
except Exception as e:
self.logger.error("Provisioning product failed", exc_info=1)
self.logger.error(e)
try:
if portfolio_id in locals() and execution_role in locals():
response = sc.disassociate_principal_from_portfolio(PortfolioId=portfolio_id, PrincipalARN=execution_role)
self.logger.debug("Principal %s disassociated from portfolio %s" % (execution_role, portfolio_id))
if constraint_id in locals and portfolio_id in locals():
response = sc.delete_constraint(Id=constraint_id)
self.logger.debug("Constraint %s deleted from portfolio %s" % (constraint_id, portfolio_id))
if product_id in locals and portfolio_id in locals():
response = sc.disassociate_product_from_portfolio(ProductId=product_id, PortfolioId=portfolio_id)
self.logger.debug("Product %s disassociated from portfolio %s" % (product_id, portfolio_id))
if product_id in locals:
response = sc.delete_product(Id=product_id)
self.logger.debug("Product %s deleted from %s" % (product_id, region))
if portfolio_id in locals():
response = sc.delete_portfolio(Id=portfolio_id)
self.logger.debug("Portfolio %s deleted from %s" % (portfolio_id, region))
except Exception:
self.logger.error("Failed to cleanup all of the Service Catalog artifacts. This will have to be manually completed on portfolio: %" % (portfolio_id))
return {'status': 'error', 'stackid': provisioned_product_id, 'region': region,
'detail': str(e), 'artifact': artifact, 'testname': testname}
def provision_product(self):
"""Creates all AWS Service Catalog provisioned products defined by the ci config
Returns:
dict: contains one or more of "success" or "error" keys, each containing a list of stackids
"""
errors = []
successes = []
for artifact in self.ci_configs.keys():
for config in self.ci_configs[artifact]:
for testname in config['tests']:
test = config['tests'][testname]
regions = self._build_regions(config, test)
template_url = self.upload_template(
artifact, test['template_file'], self.user_params['ScratchBucket'],
self.region
)
self.logger.debug("template_url: %s" % template_url)
try:
self.logger.debug("parameter_input: %s" % test['parameter_input'])
parameter_input = self._get_parameter_input(artifact, test['parameter_input'])
pool = ThreadPool(len(regions))
func = partial(
self._provision_product, artifact=artifact, testname=testname,
template_url=template_url, parameter_input=parameter_input,
role_arn=self.user_params['StackCreationRoleArn'],
key_bucket=self.user_params['KeyBucket']
)
results = pool.map(func, regions)
pool.close()
pool.join()
for result in results:
if result['status'] == 'error':
errors.append(result)
else:
successes.append(result)
except Exception:
self.logger.error("Product publishing failed for artifact %s testname %s" % (
artifact, testname), exc_info=1)
raise
self.logger.debug("Created Stacks: %s" % str([errors, successes]))
results = self.check_statuses(successes)
results["error"] += errors
return results
def upload_template(self, artifact, template_name, bucket, region):
"""Uploads a template to S3
Args:
artifact (str): artifact name
template_name (str): template filename
bucket (str): S3 bucket name
region (str): S3 bucket region