├── .gitignore ├── .metadata ├── .taskcat.yml ├── CODEOWNERS ├── LICENSE.txt ├── NOTICE.txt ├── README.md ├── functions └── source │ ├── cleanup-bucket │ ├── index.py │ └── requirements.txt │ └── git-merge │ ├── index.py │ └── requirements.txt └── templates └── taskcat-ci-entrypoint.template.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | # TaskCat 2 | taskcat_outputs/ 3 | .taskcat/ 4 | .taskcat_overrides.yml 5 | functions/packages/ 6 | *.zip 7 | 8 | # Docs 9 | docs/ 10 | index.html 11 | prod_example.html 12 | 13 | # Python 14 | .python-version 15 | venv/ 16 | env/ 17 | 18 | # macOS 19 | .DS_Store 20 | 21 | # IDE workspace settings 22 | .vscode/ 23 | .idea/ 24 | -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | language_type: cloudformation 2 | -------------------------------------------------------------------------------- /.taskcat.yml: -------------------------------------------------------------------------------- 1 | project: 2 | name: quickstart-taskcat-ci 3 | owner: quickstart-eng@amazon.com 4 | shorten_stack_name: true 5 | package_lambda: true 6 | lambda_source_path: functions/source 7 | lambda_zip_path: functions/packages 8 | template: templates/taskcat-ci-entrypoint.template.yaml 9 | regions: 10 | - af-south-1 11 | - ap-east-1 12 | - ap-northeast-1 13 | - ap-northeast-2 14 | - ap-northeast-3 15 | - ap-south-1 16 | - ap-southeast-1 17 | - ap-southeast-2 18 | - ap-southeast-3 19 | - ca-central-1 20 | - eu-central-1 21 | - eu-north-1 22 | - eu-south-1 23 | - eu-west-1 24 | - eu-west-2 25 | - eu-west-3 26 | - me-south-1 27 | - sa-east-1 28 | - us-east-1 29 | - us-east-2 30 | - us-west-1 31 | - us-west-2 32 | - us-gov-east-1 33 | - us-gov-west-1 34 | - cn-north-1 35 | - cn-northwest-1 36 | parameters: 37 | GitHubUsername: --override-- 38 | GitHubOAuthToken: --override-- 39 | GitHubOwner: --override-- 40 | GitHubRepoName: --override-- 41 | QSS3BucketName: $[taskcat_autobucket] 42 | QSS3BucketRegion: $[taskcat_current_region] 43 | tests: 44 | taskcat-ci: 45 | regions: 46 | - us-west-2 47 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @tlindsay42 @aws-quickstart/aws_quickstart_team 2 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2016-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at 4 | 5 | http://aws.amazon.com/apache2.0/ 6 | 7 | or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # quickstart-taskcat-ci 2 | ## Deprecation Notice 3 | 4 | :x: This repository is subject to deprecation in Q4 2024. For more details, [please review this announcement](https://github.com/aws-ia/.announcements/issues/1). 5 | 6 | 7 | ## This repository has been deprecated in favor of https://github.com/aws-ia/cfn-ps-taskcat-ci. 8 | ***We will archive this repository and keep it publicly available until May 1, 2024.*** 9 | -------------------------------------------------------------------------------- /functions/source/cleanup-bucket/index.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import threading 4 | import boto3 5 | import cfnresponse 6 | 7 | # set logging 8 | logger = logging.getLogger() 9 | logger.setLevel(logging.INFO) 10 | 11 | # setup client 12 | s3 = boto3.client('s3') 13 | 14 | 15 | def delete_NonVersionedobjects(bucket): 16 | logger.info('Collecting data from' + bucket) 17 | paginator = s3.get_paginator('list_objects_v2') 18 | result = paginator.paginate(Bucket=bucket) 19 | objects = [] 20 | for page in result: 21 | try: 22 | for k in page['Contents']: 23 | objects.append({'Key': k['Key']}) 24 | logger.info('deleting objects') 25 | s3.delete_objects(Bucket=bucket, Delete={ 26 | 'Objects': objects}) 27 | objects = [] 28 | except: 29 | pass 30 | logger.info('bucket is already empty') 31 | 32 | 33 | def delete_versionedobjects(bucket): 34 | logger.info('Collecting data from' + bucket) 35 | paginator = s3.get_paginator('list_object_versions') 36 | result = paginator.paginate(Bucket=bucket) 37 | objects = [] 38 | for page in result: 39 | try: 40 | for k in page['Versions']: 41 | objects.append({'Key': k['Key'], 'VersionId': k['VersionId']}) 42 | try: 43 | for k in page['DeleteMarkers']: 44 | version = k['VersionId'] 45 | key = k['Key'] 46 | objects.append({'Key': key, 'VersionId': version}) 47 | except Exception as e: 48 | logger.error(f"Error appending delete markers: '{str(e)}'") 49 | pass 50 | logger.info('deleting objects') 51 | s3.delete_objects(Bucket=bucket, Delete={'Objects': objects}) 52 | except Exception as e: 53 | logger.error(f"Error deleting S3 objects: '{str(e)}'") 54 | pass 55 | logger.info('bucket already empty') 56 | 57 | 58 | def timeout(event, context): 59 | logger.error( 60 | 'Execution is about to time out, sending failure response to CloudFormation') 61 | cfnresponse.send(event, context, cfnresponse.FAILED, {}, None) 62 | 63 | 64 | def handler(event, context): 65 | # make sure we send a failure to CloudFormation if the function is going to timeout 66 | timer = threading.Timer((context.get_remaining_time_in_millis( 67 | ) / 1000.00) - 0.5, timeout, args=[event, context]) 68 | timer.start() 69 | 70 | logger.info(f'Received event: {json.dumps(event)}') 71 | status = cfnresponse.SUCCESS 72 | try: 73 | dest_bucket = event['ResourceProperties']['DestBucket'] 74 | if event['RequestType'] == 'Delete': 75 | CheckifVersioned = s3.get_bucket_versioning(Bucket=dest_bucket) 76 | logger.info(CheckifVersioned) 77 | if 'Status' in CheckifVersioned: 78 | logger.info(CheckifVersioned['Status']) 79 | logger.info('This is a versioned Bucket') 80 | delete_versionedobjects(dest_bucket) 81 | else: 82 | logger.info('This is not a versioned bucket') 83 | delete_NonVersionedobjects(dest_bucket) 84 | else: 85 | logger.info('Nothing to do') 86 | except Exception as e: 87 | logger.error(f'Exception: {e}', exc_info=True) 88 | status = cfnresponse.FAILED 89 | finally: 90 | timer.cancel() 91 | cfnresponse.send(event, context, status, {}, None) 92 | -------------------------------------------------------------------------------- /functions/source/cleanup-bucket/requirements.txt: -------------------------------------------------------------------------------- 1 | cfnresponse>=1.1.2 2 | -------------------------------------------------------------------------------- /functions/source/git-merge/index.py: -------------------------------------------------------------------------------- 1 | # Lambda function to merge git branches 2 | import json 3 | import logging 4 | import requests 5 | import boto3 6 | import os 7 | 8 | # set logging 9 | logger = logging.getLogger() 10 | logger.setLevel(logging.INFO) 11 | 12 | # setup client 13 | region = os.environ['AWS_REGION'] 14 | secretsmanager = boto3.client('secretsmanager', region_name=region) 15 | 16 | # global constants 17 | merge_endpoint = 'https://api.github.com/repos/{owner}/{repo}/merges' 18 | 19 | # setup client 20 | region = os.environ['AWS_REGION'] 21 | ssm = boto3.client('ssm', region_name=region) 22 | code_pipeline = boto3.client('codepipeline', region_name=region) 23 | 24 | 25 | def put_job_success(job: str, message: str): 26 | """Notify CodePipeline of a successful job 27 | 28 | Args: 29 | job: The CodePipeline job ID 30 | message: A message to be logged relating to the job status 31 | 32 | Raises: 33 | Exception: Any exception thrown by .put_job_success_result() 34 | 35 | """ 36 | logger.info(f'Putting job success. {message}') 37 | code_pipeline.put_job_success_result(jobId=job) 38 | 39 | 40 | def put_job_failure(job: str, message: str): 41 | """Notify CodePipeline of a failed job 42 | 43 | Args: 44 | job: The CodePipeline job ID 45 | message: A message to be logged relating to the job status 46 | 47 | Raises: 48 | Exception: Any exception thrown by .put_job_failure_result() 49 | 50 | """ 51 | logger.info(f'Putting job failure. {message}') 52 | failure_details = {'message': message, 'type': 'JobFailed'} 53 | code_pipeline.put_job_failure_result( 54 | jobId=job, failureDetails=failure_details) 55 | 56 | 57 | def get_user_params(job_data): 58 | """Decodes the JSON user parameters and validates the required properties. 59 | 60 | Args: 61 | job_data: The job data structure containing the UserParameters string which should be a valid JSON structure 62 | 63 | Returns: 64 | The JSON parameters decoded as a dictionary. 65 | 66 | Raises: 67 | Exception: The JSON can't be decoded or a property is missing. 68 | 69 | """ 70 | try: 71 | # Get the user parameters which contain the base branch name, branch to be merged, repo owner and repo name 72 | user_parameters = job_data['actionConfiguration']['configuration']['UserParameters'] 73 | decoded_parameters = json.loads(user_parameters) 74 | 75 | except Exception as e: 76 | # We're expecting the user parameters to be encoded as JSON 77 | # so we can pass multiple values. If the JSON can't be decoded 78 | # then fail the job with a helpful message. 79 | raise Exception('UserParameters could not be decoded as JSON') 80 | 81 | if 'baseBranch' not in decoded_parameters: 82 | # Validate that the base branch name is provided, otherwise fail the job 83 | # with a helpful message. 84 | raise Exception( 85 | 'Your UserParameters JSON must include the base branch name') 86 | 87 | if 'headBranch' not in decoded_parameters: 88 | # Validate that the head branch name is provided, otherwise fail the job 89 | # with a helpful message. 90 | raise Exception( 91 | 'Your UserParameters JSON must include the head branch name') 92 | 93 | if 'owner' not in decoded_parameters: 94 | # Validate that the repo owner is provided, otherwise fail the job 95 | # with a helpful message. 96 | raise Exception('Your UserParameters JSON must include the repo owner') 97 | 98 | if 'repo' not in decoded_parameters: 99 | # Validate that the repo name is provided, otherwise fail the job 100 | # with a helpful message. 101 | raise Exception('Your UserParameters JSON must include the repo name') 102 | 103 | if 'secretsManagerArn' not in decoded_parameters: 104 | # Validate that the Secrets Manager ARN is provided, otherwise fail the 105 | # job with a helpful message. 106 | raise Exception( 107 | 'Your UserParameters JSON must include the Secrets Manager ARN') 108 | 109 | return decoded_parameters 110 | 111 | 112 | def handler(event, context): 113 | """ 114 | The Lambda function handler 115 | 116 | Merge the develop branch into master branch of the github repo. 117 | 118 | Args: 119 | event: The event passed by Lambda 120 | context: The context passed by Lambda 121 | 122 | """ 123 | logger.info(f'Received event: {json.dumps(event)}') 124 | 125 | try: 126 | # Extract the Job ID 127 | job_id = event['CodePipeline.job']['id'] 128 | 129 | # Extract the Job Data 130 | job_data = event['CodePipeline.job']['data'] 131 | 132 | # Extract the params 133 | params = get_user_params(job_data) 134 | 135 | repo_owner = params['owner'] 136 | repo_name = params['repo'] 137 | base_branch = params['baseBranch'] 138 | head_branch = params['headBranch'] 139 | # token_id = params['tokenId'] 140 | secretsmanager_arn = params['secretsManagerArn'] 141 | 142 | # Get secret from Secrets Manager 143 | secret = json.loads(secretsmanager.get_secret_value( 144 | SecretId=secretsmanager_arn)['SecretString']) 145 | 146 | # Get GitHub token from secret 147 | github_token = secret['Token'] 148 | 149 | # Construct merge endpoint 150 | global merge_endpoint 151 | merge_endpoint = merge_endpoint.format( 152 | owner=repo_owner, repo=repo_name) 153 | 154 | # Construct post data 155 | data = { 156 | 'base': base_branch, 157 | 'head': head_branch 158 | } 159 | 160 | # Construct header 161 | headers = { 162 | 'Content-Type': 'application/json', 163 | 'Authorization': f'token {github_token}' 164 | } 165 | 166 | # Submit request 167 | result = requests.post( 168 | merge_endpoint, data=json.dumps(data), headers=headers) 169 | logger.debug(result) 170 | 171 | if result.status_code == requests.codes.created: 172 | # Merge completed successfully. 173 | message = 'Merge completed successfully.' 174 | logger.info(message) 175 | put_job_success(job_id, message) 176 | elif result.status_code == requests.codes.no_content: 177 | # Merge not needed. Base already contains the head, nothing to merge. 178 | message = 'Nothing to merge.' 179 | logger.info(message) 180 | put_job_success(job_id, message) 181 | else: 182 | # Merge failed. 183 | status = str(result.raise_for_status()) 184 | logger.error(status) 185 | put_job_failure(job_id, f'Merge failed: {status}') 186 | 187 | except Exception as e: 188 | # If any other exceptions which we didn't expect are raised 189 | # then fail the job and log the exception message. 190 | logger.error(f'Function failed due to exception: {e}') 191 | put_job_failure(job_id, f'Function exception: {str(e)}') 192 | 193 | logger.info('Function execution complete') 194 | return True 195 | -------------------------------------------------------------------------------- /functions/source/git-merge/requirements.txt: -------------------------------------------------------------------------------- 1 | cfnresponse>=1.1.2 2 | requests>=2.27.0 3 | -------------------------------------------------------------------------------- /templates/taskcat-ci-entrypoint.template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: >- 3 | CloudFormation template for deploying a TaskCat CI/CD pipeline for testing changes to AWS CloudFormation templates stored in a GitHub repository. (qs-1ops82lkf) 4 | Metadata: 5 | LICENSE: Apache License, Version 2.0 6 | AWS::CloudFormation::Interface: 7 | ParameterGroups: 8 | - Label: 9 | default: GitHub configuration 10 | Parameters: 11 | - GitHubUsername 12 | - GitHubOAuthToken 13 | - GitHubOwner 14 | - GitHubRepoName 15 | - SourceBranch 16 | - ReleaseBranch 17 | - Label: 18 | default: AWS Solution configuration 19 | Parameters: 20 | - QSS3BucketName 21 | - QSS3KeyPrefix 22 | ParameterLabels: 23 | GitHubUsername: 24 | default: User name 25 | GitHubOAuthToken: 26 | default: Personal access token 27 | GitHubOwner: 28 | default: Repository owner 29 | GitHubRepoName: 30 | default: Repository name 31 | SourceBranch: 32 | default: Source branch name 33 | ReleaseBranch: 34 | default: Release branch name 35 | QSS3BucketName: 36 | default: AWS Solution S3 bucket name 37 | QSS3KeyPrefix: 38 | default: AWS Solution S3 key prefix 39 | Parameters: 40 | GitHubUsername: 41 | Type: String 42 | Description: >- 43 | GitHub user name to use as the continuous integration (CI) service account. 44 | GitHubOAuthToken: 45 | Type: String 46 | Description: >- 47 | GitHub personal access token for the continuous integration (CI) service account user. This token must be granted the "repo" and "admin:repo_hook" permission sets. Refer to https://github.com/settings/tokens. 48 | NoEcho: true 49 | GitHubOwner: 50 | Type: String 51 | Description: >- 52 | GitHub owner (user name or organization) where the repository is located. Refer to https://docs.github.com/en/repositories/creating-and-managing-repositories/about-repositories. 53 | GitHubRepoName: 54 | Type: String 55 | Description: Name of the source repository to monitor. 56 | SourceBranch: 57 | Type: String 58 | Description: Name of the source branch to monitor. 59 | Default: develop 60 | ReleaseBranch: 61 | Type: String 62 | Description: >- 63 | Release branch name. Commits in the source branch merge into this branch. 64 | Default: main 65 | QSS3BucketName: 66 | AllowedPattern: ^[0-9a-z]+([0-9a-z-\.]*[0-9a-z])*$ 67 | ConstraintDescription: >- 68 | The S3 bucket name can include numbers, lowercase letters, 69 | and hyphens (-), but it cannot start or end with a hyphen. 70 | Default: aws-quickstart 71 | Description: >- 72 | Name of the S3 bucket for your copy of the deployment assets. Keep the default name unless you are customizing the template. Changing the name updates code references to point to a new location. 73 | MinLength: 3 74 | MaxLength: 63 75 | Type: String 76 | QSS3KeyPrefix: 77 | AllowedPattern: ^([0-9a-zA-Z!-_\.\*'\(\)/]+/)*$ 78 | ConstraintDescription: >- 79 | The S3 key prefix can include numbers, lowercase letters, uppercase letters, hyphens (-), underscores (_), periods (.), asterisks (*), single quotes ('), open parenthesis ((), close parenthesis ()), and forward slashes (/). End the prefix with a forward slash. 80 | Default: quickstart-taskcat-ci/ 81 | Description: >- 82 | S3 key prefix that is used to simulate a folder for your copy of the deployment assets. Keep the default prefix unless you are customizing the template. Changing the prefix updates code references to point to a new location. 83 | Type: String 84 | Conditions: 85 | UsingDefaultBucket: !Equals [!Ref QSS3BucketName, aws-quickstart] 86 | Resources: 87 | ArtifactBucket: 88 | Type: AWS::S3::Bucket 89 | Properties: 90 | AccessControl: Private 91 | LifecycleConfiguration: 92 | Rules: 93 | - NoncurrentVersionExpirationInDays: 30 94 | Status: Enabled 95 | VersioningConfiguration: 96 | Status: Enabled 97 | S3CleanUpRole: 98 | Type: AWS::IAM::Role 99 | Properties: 100 | Path: / 101 | AssumeRolePolicyDocument: 102 | Version: 2012-10-17 103 | Statement: 104 | - Effect: Allow 105 | Action: sts:AssumeRole 106 | Principal: 107 | Service: lambda.amazonaws.com 108 | Policies: 109 | - PolicyName: EmptyArtifactBucket 110 | PolicyDocument: 111 | Version: 2012-10-17 112 | Statement: 113 | - Sid: ManageBucketObjects 114 | Effect: Allow 115 | Action: 116 | - s3:DeleteObject 117 | - s3:DeleteObjectVersion 118 | - s3:GetObject 119 | - s3:GetObjectVersion 120 | - s3:PutObject 121 | Resource: !Sub ${ArtifactBucket.Arn}/* 122 | - Sid: ListBucket 123 | Effect: Allow 124 | Action: 125 | - s3:GetBucketVersioning 126 | - s3:ListBucket 127 | - s3:ListBucketVersions 128 | Resource: !GetAtt ArtifactBucket.Arn 129 | ManagedPolicyArns: 130 | - !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole 131 | CleanUpS3BucketFunction: 132 | Type: AWS::Lambda::Function 133 | Properties: 134 | Description: Empty the specified S3 bucket 135 | Handler: index.handler 136 | Role: !GetAtt S3CleanUpRole.Arn 137 | Runtime: python3.9 138 | Timeout: 240 139 | Code: 140 | S3Bucket: !If [UsingDefaultBucket, !Sub '${QSS3BucketName}-${AWS::Region}', !Ref QSS3BucketName] 141 | S3Key: !Sub ${QSS3KeyPrefix}functions/packages/cleanup-bucket/lambda.zip 142 | CleanUpS3Bucket: 143 | Type: AWS::CloudFormation::CustomResource 144 | Properties: 145 | DestBucket: !Ref ArtifactBucket 146 | ServiceToken: !GetAtt CleanUpS3BucketFunction.Arn 147 | Secrets: 148 | Type: AWS::SecretsManager::Secret 149 | Properties: 150 | Description: TaskCat CI secrets. 151 | SecretString: !Sub >- 152 | { 153 | "Token": "${GitHubOAuthToken}", 154 | "Username": "${GitHubUsername}" 155 | } 156 | GitMergeRole: 157 | Type: AWS::IAM::Role 158 | Properties: 159 | AssumeRolePolicyDocument: 160 | Version: 2012-10-17 161 | Statement: 162 | - Effect: Allow 163 | Principal: 164 | Service: lambda.amazonaws.com 165 | Action: sts:AssumeRole 166 | Path: / 167 | Policies: 168 | - PolicyName: GitMergePolicy 169 | PolicyDocument: 170 | Version: 2012-10-17 171 | Statement: 172 | - Sid: GetCodePipelineData 173 | Effect: Allow 174 | Action: 175 | - codepipeline:GetPipeline 176 | - codepipeline:GetPipelineExecution 177 | - codepipeline:GetPipelineState 178 | - codepipeline:ListPipelineExecutions 179 | - codepipeline:ListPipelines 180 | Resource: !Sub arn:${AWS::Partition}:codepipeline:${AWS::Region}:${AWS::AccountId}:* 181 | - Sid: PutCodePipelineJobResults 182 | Effect: Allow 183 | Action: 184 | - codepipeline:GetJobDetails 185 | - codepipeline:PutJobFailureResult 186 | - codepipeline:PutJobSuccessResult 187 | Resource: '*' 188 | - Sid: ListArtifactBucket 189 | Effect: Allow 190 | Action: 191 | - s3:GetBucketVersioning 192 | - s3:ListBucket 193 | - s3:ListBucketVersions 194 | Resource: !GetAtt ArtifactBucket.Arn 195 | - Sid: GetArtifactBucketObjects 196 | Effect: Allow 197 | Action: s3:GetObject 198 | Resource: !Sub ${ArtifactBucket.Arn}/* 199 | - Sid: GetSecrets 200 | Effect: Allow 201 | Action: secretsmanager:GetSecretValue 202 | Resource: !Ref Secrets 203 | ManagedPolicyArns: 204 | - !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole 205 | GitMergeFunction: 206 | Type: AWS::Lambda::Function 207 | Properties: 208 | Code: 209 | S3Bucket: !If [UsingDefaultBucket, !Sub '${QSS3BucketName}-${AWS::Region}', !Ref QSS3BucketName] 210 | S3Key: !Sub ${QSS3KeyPrefix}functions/packages/git-merge/lambda.zip 211 | Description: Merge GitHub branches 212 | Handler: index.handler 213 | Role: !GetAtt GitMergeRole.Arn 214 | Runtime: python3.9 215 | Timeout: 30 216 | CodeBuildServiceRole: 217 | Type: AWS::IAM::Role 218 | Properties: 219 | Path: / 220 | AssumeRolePolicyDocument: 221 | Version: 2012-10-17 222 | Statement: 223 | - Effect: Allow 224 | Action: sts:AssumeRole 225 | Principal: 226 | Service: codebuild.amazonaws.com 227 | ManagedPolicyArns: 228 | - !Sub arn:${AWS::Partition}:iam::aws:policy/AdministratorAccess 229 | CodeBuild: 230 | Type: AWS::CodeBuild::Project 231 | Properties: 232 | Description: !Sub >- 233 | Submit build jobs for ${GitHubRepoName} as part of a CI/CD pipeline. 234 | ServiceRole: !GetAtt CodeBuildServiceRole.Arn 235 | Artifacts: 236 | Type: CODEPIPELINE 237 | Environment: 238 | Type: LINUX_CONTAINER 239 | ComputeType: BUILD_GENERAL1_SMALL 240 | Image: aws/codebuild/standard:5.0 241 | EnvironmentVariables: 242 | - Name: ARTIFACT_BUCKET 243 | Value: !Ref ArtifactBucket 244 | - Name: PROJECT_NAME 245 | Value: !Ref GitHubRepoName 246 | - Name: PROJECT_OWNER 247 | Value: !Ref GitHubOwner 248 | - Name: SOURCE_BRANCH 249 | Value: !Ref SourceBranch 250 | PrivilegedMode: true 251 | Visibility: PRIVATE 252 | Source: 253 | Type: CODEPIPELINE 254 | GitCloneDepth: 1 255 | BuildSpec: !Sub | 256 | version: 0.2 257 | 258 | env: 259 | shell: bash 260 | secrets-manager: 261 | GITHUB_TOKEN: ${Secrets}:Token 262 | GITHUB_USERNAME: ${Secrets}:Username 263 | TASKCAT_OVERRIDES: arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:${GitHubRepoName} 264 | 265 | phases: 266 | install: 267 | runtime-versions: 268 | python: 3.x 269 | commands: 270 | - echo "Entered the install phase..." 271 | - apt-get -qy update 272 | - echo "Installing system dependencies..." 273 | - apt-get -qy install zip gzip tar 274 | - echo "Installing python dependencies..." 275 | - pip3 -q install cfn-lint==0.66.1 pre-commit taskcat yq 276 | - echo "Configuring taskcat..." 277 | - | 278 | cat << EOF > ~/.taskcat.yml 279 | general: 280 | s3_regional_buckets: true 281 | EOF 282 | - echo "Configuring pre-commit..." 283 | - | 284 | cat << EOF > ./.pre-commit-config.yaml 285 | fail_fast: false 286 | minimum_pre_commit_version: 2.6.0 287 | repos: 288 | - repo: https://github.com/aws-quickstart/qs-cfn-lint-rules 289 | rev: d4f788d6df2c62c763ecb1182ef9df623db538a2 290 | hooks: 291 | - id: qs-cfn-lint-wrapped 292 | files: ^templates/.* 293 | args: 294 | - --format=pretty 295 | require_serial: true 296 | EOF 297 | pre_build: 298 | commands: 299 | - echo "Entered the pre_build phase..." 300 | - echo "Current directory is $CODEBUILD_SRC_DIR" 301 | - ls -lA 302 | - dirname=${!PWD##*/} 303 | - echo "Directory name $dirname" 304 | - cd .. 305 | - mv $dirname $PROJECT_NAME 306 | - ls -lA 307 | - cd $PROJECT_NAME 308 | - echo "Temporarily adding git credential store..." 309 | - echo "https://$GITHUB_USERNAME:$GITHUB_TOKEN@github.com" > ~/.git-credentials 310 | - git config --global credential.helper store 311 | - git config --global url."https://github.com/".insteadOf "git@github.com:" 312 | - git config --global init.defaultBranch ${ReleaseBranch} 313 | - git init 314 | - git remote add origin https://github.com/$PROJECT_OWNER/$PROJECT_NAME.git 315 | - git fetch 316 | - git checkout --force --track origin/$SOURCE_BRANCH 317 | - git submodule init 318 | - git submodule update --init --recursive 319 | - echo "Creating TaskCat overrides file..." 320 | - echo $TASKCAT_OVERRIDES | yq -y > ./.taskcat_overrides.yml 321 | - ls -lA 322 | - echo "Verifying TaskCat installation..." 323 | - taskcat 324 | - echo "Removing git credential store..." 325 | - rm -f ~/.git-credentials 326 | build: 327 | commands: 328 | - echo "Entered the build phase..." 329 | - echo "Running lint tests..." 330 | - pre-commit run --all-files 331 | - echo "Running TaskCat tests..." 332 | - taskcat test run --minimal-output --lint-disable 333 | - | 334 | if $(grep -Fq "CREATE_FAILED" taskcat_outputs/index.html) 335 | then 336 | echo "Build failed!" 337 | exit 1 338 | else 339 | echo "Build passed!" 340 | exit 0 341 | fi 342 | finally: 343 | - ls -1 taskcat_outputs 344 | - ls -1 taskcat_outputs | while read LOG; do cat taskcat_outputs/$LOG; done 345 | - >- # Do not remove 346 | echo "Zipping and uploading report to S3 bucket: '$ARTIFACT_BUCKET'..." 347 | - zip -r taskcat_report.zip taskcat_outputs 348 | - aws s3 cp taskcat_report.zip s3://$ARTIFACT_BUCKET/taskcat_reports/$CODEBUILD_BUILD_ID.zip 349 | CodePipelineServiceRole: 350 | Type: AWS::IAM::Role 351 | Properties: 352 | Path: / 353 | AssumeRolePolicyDocument: 354 | Version: 2012-10-17 355 | Statement: 356 | - Effect: Allow 357 | Action: sts:AssumeRole 358 | Principal: 359 | Service: codepipeline.amazonaws.com 360 | Policies: 361 | - PolicyName: TaskCat-CICD-CodePipelineService 362 | PolicyDocument: 363 | Version: 2012-10-17 364 | Statement: 365 | - Sid: ListArtifact 366 | Effect: Allow 367 | Action: 368 | - s3:GetBucketVersioning 369 | - s3:ListBucket 370 | - s3:ListBucketVersions 371 | Resource: !GetAtt ArtifactBucket.Arn 372 | - Sid: PutArtifacts 373 | Effect: Allow 374 | Action: 375 | - s3:GetObject 376 | - s3:GetObjectVersion 377 | - s3:PutObject 378 | Resource: !Sub ${ArtifactBucket.Arn}/* 379 | - Sid: ManageCloudFormation 380 | Effect: Allow 381 | Action: 382 | - cloudformation:CreateChangeSet 383 | - cloudformation:CreateStack 384 | - cloudformation:DeleteChangeSet 385 | - cloudformation:DeleteStack 386 | - cloudformation:DescribeChangeSet 387 | - cloudformation:DescribeStacks 388 | - cloudformation:ExecuteChangeSet 389 | - cloudformation:SetStackPolicy 390 | - cloudformation:UpdateStack 391 | - cloudformation:ValidateTemplate 392 | Resource: !Sub arn:${AWS::Partition}:cloudformation:*:*:* 393 | - Sid: PassRoleToCloudFormation 394 | Effect: Allow 395 | Action: iam:PassRole 396 | Resource: '*' 397 | Condition: 398 | StringEquals: 399 | iam:PassedToService: cloudformation.amazonaws.com 400 | - Sid: StartBuilds 401 | Effect: Allow 402 | Action: 403 | - codebuild:BatchGetBuilds 404 | - codebuild:StartBuild 405 | Resource: !GetAtt CodeBuild.Arn 406 | - Sid: GetLambda 407 | Effect: Allow 408 | Action: 409 | - lambda:GetAccountSettings 410 | - lambda:GetAlias 411 | - lambda:GetEventSourceMapping 412 | - lambda:GetFunction 413 | - lambda:GetFunctionConfiguration 414 | - lambda:GetPolicy 415 | - lambda:InvokeFunction 416 | - lambda:ListAliases 417 | - lambda:ListEventSourceMappings 418 | - lambda:ListFunctions 419 | - lambda:ListTags 420 | - lambda:ListVersionsByFunction 421 | Resource: arn:*:lambda:*:*:* 422 | ManagedPolicyArns: 423 | - !Sub arn:${AWS::Partition}:iam::aws:policy/AWSCodeCommitFullAccess 424 | CodePipeline: 425 | Type: AWS::CodePipeline::Pipeline 426 | Properties: 427 | ArtifactStore: 428 | Type: S3 429 | Location: !Ref ArtifactBucket 430 | RoleArn: !GetAtt CodePipelineServiceRole.Arn 431 | Stages: 432 | - Name: Source 433 | Actions: 434 | - Name: GitHub 435 | InputArtifacts: [] 436 | ActionTypeId: 437 | Category: Source 438 | Owner: ThirdParty 439 | Version: 1 440 | Provider: GitHub 441 | OutputArtifacts: 442 | - Name: Source 443 | Configuration: 444 | Owner: !Ref GitHubOwner 445 | Repo: !Ref GitHubRepoName 446 | Branch: !Ref SourceBranch 447 | OAuthToken: !Ref GitHubOAuthToken 448 | RunOrder: 1 449 | - Name: Build 450 | Actions: 451 | - Name: CodeBuild 452 | InputArtifacts: 453 | - Name: Source 454 | ActionTypeId: 455 | Category: Build 456 | Owner: AWS 457 | Version: 1 458 | Provider: CodeBuild 459 | OutputArtifacts: [] 460 | Configuration: 461 | ProjectName: !Ref CodeBuild 462 | RunOrder: 2 463 | - Name: Deploy 464 | Actions: 465 | - Name: Git-merge 466 | ActionTypeId: 467 | Category: Invoke 468 | Owner: AWS 469 | Version: 1 470 | Provider: Lambda 471 | Configuration: 472 | FunctionName: !Ref GitMergeFunction 473 | UserParameters: !Sub >- 474 | { 475 | "owner": "${GitHubOwner}", 476 | "repo": "${GitHubRepoName}", 477 | "baseBranch": "${ReleaseBranch}", 478 | "headBranch": "${SourceBranch}", 479 | "secretsManagerArn": "${Secrets}" 480 | } 481 | RunOrder: 3 482 | Outputs: 483 | CodePipelineURL: 484 | Description: The URL of the created pipeline. 485 | Value: !Sub https://${AWS::Region}.console.aws.amazon.com/codepipeline/home?region=${AWS::Region}#/view/${CodePipeline} 486 | TaskCatReports: 487 | Description: Path to the TaskCat report. Each report is named as CODEBUILD_BUILD_ID.zip. 488 | Value: !Sub s3://${ArtifactBucket}/taskcat_reports/ 489 | Postdeployment: 490 | Description: See the deployment guide for postdeployment steps. 491 | Value: https://fwd.aws/BrGzY? 492 | --------------------------------------------------------------------------------