├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── Pipeline ├── DevAccount │ └── toolsacct-codepipeline-codecommit.yaml ├── TestAccount │ └── toolsacct-codepipeline-cloudformation-deployer.yaml └── ToolsAcct │ ├── code-pipeline.yaml │ └── pre-reqs.yaml ├── README.md ├── SampleLambda ├── README.md ├── lambda-cloudformation.yaml └── scripts │ ├── __pycache__ │ └── test_module.cpython-37.pyc │ ├── actions.json │ ├── iam_policy.json │ ├── index.py │ ├── requirements.txt │ ├── source.txt │ └── test_module.py └── single-click-cross-account-pipeline.sh /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2020 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 | 9 | iam-policy-tester-pipeline 10 | Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 11 | -------------------------------------------------------------------------------- /Pipeline/DevAccount/toolsacct-codepipeline-codecommit.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 3 | # the License. A copy of the License is located at 4 | # http://aws.amazon.com/apache2.0/ 5 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 6 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 7 | # limitations under the License. 8 | 9 | AWSTemplateFormatVersion: '2010-09-09' 10 | Description: Cross Account Role to Allow Access to CodePipeline in Tools Account 11 | Parameters: 12 | ToolsAccount: 13 | Description: AWS AccountNumber for tools account 14 | Type: Number 15 | CMKARN: 16 | Description: ARN of the KMS CMK creates in Tools account 17 | Type: String 18 | Resources: 19 | Role: 20 | Type: AWS::IAM::Role 21 | Properties: 22 | RoleName: !Sub ToolsAcctCodePipelineCodeCommitRole 23 | AssumeRolePolicyDocument: 24 | Version: 2012-10-17 25 | Statement: 26 | - 27 | Effect: Allow 28 | Principal: 29 | AWS: 30 | - !Ref ToolsAccount 31 | Action: 32 | - sts:AssumeRole 33 | Path: / 34 | 35 | Policy: 36 | Type: AWS::IAM::Policy 37 | Properties: 38 | PolicyName: !Sub ToolsAcctCodePipelineCodeCommitPolicy 39 | PolicyDocument: 40 | Version: 2012-10-17 41 | Statement: 42 | - 43 | Effect: Allow 44 | Action: 45 | - codecommit:BatchGetRepositories 46 | - codecommit:Get* 47 | - codecommit:GitPull 48 | - codecommit:List* 49 | - codecommit:CancelUploadArchive 50 | - codecommit:UploadArchive 51 | - s3:* 52 | Resource: "*" 53 | - 54 | Effect: Allow 55 | Action: 56 | - kms:* 57 | Resource: !Ref CMKARN 58 | Roles: 59 | - 60 | !Ref Role -------------------------------------------------------------------------------- /Pipeline/TestAccount/toolsacct-codepipeline-cloudformation-deployer.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 3 | # the License. A copy of the License is located at 4 | # http://aws.amazon.com/apache2.0/ 5 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 6 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 7 | # limitations under the License. 8 | 9 | AWSTemplateFormatVersion: '2010-09-09' 10 | Description: Role to be assumed by CodePipeline service cross account 11 | Parameters: 12 | S3Bucket: 13 | Description: S3 Bucket in Tools Account, which holds the artifacts built by codebuild 14 | Type: String 15 | ToolsAccount: 16 | Description: AWS AccountNumber for Tools 17 | Type: Number 18 | CMKARN: 19 | Description: ARN of the KMS CMK creates in Tools account 20 | Type: String 21 | Resources: 22 | CFRole: 23 | Type: AWS::IAM::Role 24 | Properties: 25 | RoleName: !Sub ToolsAcctCodePipelineCloudFormationRole 26 | AssumeRolePolicyDocument: 27 | Version: 2012-10-17 28 | Statement: 29 | - 30 | Effect: Allow 31 | Principal: 32 | AWS: 33 | - !Ref ToolsAccount 34 | Action: 35 | - sts:AssumeRole 36 | Path: / 37 | CFPolicy: 38 | Type: AWS::IAM::Policy 39 | Properties: 40 | PolicyName: !Sub ToolsAcctCodePipelineCloudFormationPolicy 41 | PolicyDocument: 42 | Version: 2012-10-17 43 | Statement: 44 | - 45 | Effect: Allow 46 | Action: 47 | - cloudformation:* 48 | - s3:* 49 | - iam:PassRole 50 | Resource: "*" 51 | - 52 | Effect: Allow 53 | Action: 54 | - kms:* 55 | Resource: !Ref CMKARN 56 | Roles: 57 | - 58 | !Ref CFRole 59 | CFDeployerRole: 60 | Type: AWS::IAM::Role 61 | Properties: 62 | RoleName: !Sub cloudformationdeployer-role 63 | AssumeRolePolicyDocument: 64 | Version: 2012-10-17 65 | Statement: 66 | - 67 | Effect: Allow 68 | Principal: 69 | Service: 70 | - cloudformation.amazonaws.com 71 | Action: 72 | - sts:AssumeRole 73 | Path: / 74 | CFDeployerPolicy: 75 | Type: AWS::IAM::Policy 76 | Properties: 77 | PolicyName: !Sub cloudformationdeployer-policy 78 | PolicyDocument: 79 | Version: 2012-10-17 80 | Statement: 81 | - 82 | Effect: Allow 83 | Action: 84 | - lambda:AddPermission 85 | - lambda:CreateFunction 86 | - lambda:DeleteFunction 87 | - lambda:InvokeFunction 88 | - lambda:RemovePermission 89 | - lambda:UpdateFunctionCode 90 | - lambda:GetFunctionConfiguration 91 | - lambda:GetFunction 92 | - lambda:UpdateFunctionConfiguration 93 | - apigateway:* 94 | - events:* # Required for the sample lambda function to work 95 | - iam:CreateRole 96 | - iam:CreatePolicy 97 | - iam:GetRole 98 | - iam:DeleteRole 99 | - iam:PutRolePolicy 100 | - iam:PassRole 101 | - iam:DeleteRolePolicy 102 | - iam:DetachRolePolicy 103 | - iam:AttachRolePolicy 104 | - cloudformation:* 105 | Resource: "*" 106 | - 107 | Effect: Allow 108 | Action: 109 | - s3:PutObject 110 | - s3:GetBucketPolicy 111 | - s3:GetObject 112 | - s3:ListBucket 113 | Resource: 114 | - !Join ['',['arn:aws:s3:::',!Ref S3Bucket, '/*']] 115 | - !Join ['',['arn:aws:s3:::',!Ref S3Bucket]] 116 | Roles: 117 | - 118 | !Ref CFDeployerRole -------------------------------------------------------------------------------- /Pipeline/ToolsAcct/code-pipeline.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 3 | # the License. A copy of the License is located at 4 | # http://aws.amazon.com/apache2.0/ 5 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 6 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 7 | # limitations under the License. 8 | 9 | AWSTemplateFormatVersion: '2010-09-09' 10 | Description: CodePipeline for the Sample Lambda Function (uksb-1qfmusbr5) 11 | Parameters: 12 | ProjectName: 13 | Description: Name of the Project 14 | Type: String 15 | Default: sample-lambda 16 | S3Bucket: 17 | Description: S3 Bucket, which will hold the artifacts 18 | Type: String 19 | DevAccount: 20 | Description: AWS AccountNumber for dev 21 | Type: Number 22 | TestAccount: 23 | Description: AWS AccountNumber for test 24 | Type: Number 25 | ProductionAccount: 26 | Description: AWS AccountNumber for production 27 | Type: Number 28 | CMKARN: 29 | Description: ARN of the KMS CMK creates in Tools account 30 | Type: String 31 | CrossAccountCondition: 32 | Description: Conditionally creates the resources for cross account access 33 | Type: String 34 | Default: false 35 | 36 | Conditions: 37 | AddCodeBuildResource: !Equals [ !Ref CrossAccountCondition, true ] 38 | 39 | Resources: 40 | BuildProjectRole: 41 | Type: AWS::IAM::Role 42 | Properties: 43 | RoleName: !Sub ${ProjectName}-CodeBuildRole 44 | AssumeRolePolicyDocument: 45 | Version: 2012-10-17 46 | Statement: 47 | - 48 | Effect: Allow 49 | Principal: 50 | Service: 51 | - codebuild.amazonaws.com 52 | Action: 53 | - sts:AssumeRole 54 | Path: / 55 | 56 | BuildProjectPolicy: 57 | Type: AWS::IAM::Policy 58 | DependsOn: S3BucketPolicy 59 | Properties: 60 | PolicyName: !Sub ${ProjectName}-CodeBuildPolicy 61 | PolicyDocument: 62 | Version: 2012-10-17 63 | Statement: 64 | - 65 | Effect: Allow 66 | Action: 67 | - s3:PutObject 68 | - s3:GetBucketPolicy 69 | - s3:GetObject 70 | - s3:ListBucket 71 | Resource: 72 | - !Join ['',['arn:aws:s3:::',!Ref S3Bucket, '/*']] 73 | - !Join ['',['arn:aws:s3:::',!Ref S3Bucket]] 74 | - 75 | Effect: Allow 76 | Action: 77 | - kms:* 78 | Resource: !Ref CMKARN 79 | - 80 | Effect: Allow 81 | Action: 82 | - logs:CreateLogGroup 83 | - logs:CreateLogStream 84 | - logs:PutLogEvents 85 | Resource: arn:aws:logs:*:*:* 86 | - 87 | Effect: Allow 88 | Action: 89 | - iam:SimulateCustomPolicy 90 | - iam:SimulatePrincipalPolicy 91 | 92 | Resource: "*" 93 | Roles: 94 | - 95 | !Ref BuildProjectRole 96 | 97 | BuildProject: 98 | Type: AWS::CodeBuild::Project 99 | Properties: 100 | Description: !Sub 101 | - '${Project}/BuildCBProject' 102 | - { Project: !Ref ProjectName } 103 | EncryptionKey: !Ref CMKARN 104 | ServiceRole: !GetAtt BuildProjectRole.Arn 105 | Artifacts: 106 | Type: CODEPIPELINE 107 | Environment: 108 | Type: LINUX_CONTAINER 109 | ComputeType: BUILD_GENERAL1_SMALL 110 | Image: aws/codebuild/standard:2.0 111 | EnvironmentVariables: 112 | - Name: S3Bucket 113 | Value: !Ref S3Bucket 114 | - Name: KMSKey 115 | Value: !Ref CMKARN 116 | Source: 117 | Type: CODEPIPELINE 118 | BuildSpec: | 119 | version: 0.2 120 | phases: 121 | install: 122 | runtime-versions: 123 | python: 3.7 124 | commands: 125 | - printenv 126 | - ls -R 127 | - pip install -r scripts/requirements.txt -t "$PWD" 128 | build: 129 | commands: 130 | - aws cloudformation package --template-file lambda-cloudformation.yaml --s3-bucket $S3Bucket --s3-prefix sample-lambda/codebuild --output-template-file samtemplate.yaml 131 | artifacts: 132 | files: 133 | - samtemplate.yaml 134 | - scripts/* 135 | discard-paths: yes 136 | 137 | TimeoutInMinutes: 10 138 | Tags: 139 | - Key: Name 140 | Value: !Ref ProjectName 141 | 142 | TestProject: 143 | Type: AWS::CodeBuild::Project 144 | Properties: 145 | Description: !Sub 146 | - '${Project}/TestCBProject' 147 | - { Project: !Ref ProjectName } 148 | EncryptionKey: !Ref CMKARN 149 | ServiceRole: !GetAtt BuildProjectRole.Arn 150 | Artifacts: 151 | Type: CODEPIPELINE 152 | Environment: 153 | Type: LINUX_CONTAINER 154 | ComputeType: BUILD_GENERAL1_SMALL 155 | Image: aws/codebuild/standard:2.0 156 | Source: 157 | Type: CODEPIPELINE 158 | BuildSpec: | 159 | version: 0.2 160 | phases: 161 | install: 162 | runtime-versions: 163 | python: 3.7 164 | commands: 165 | - printenv 166 | - ls -R 167 | - pip install -r requirements.txt -t "$PWD" 168 | build: 169 | commands: 170 | - python -m unittest test_module.py 171 | TimeoutInMinutes: 10 172 | Tags: 173 | - Key: Name 174 | Value: !Ref ProjectName 175 | 176 | PipeLineRole: 177 | Type: AWS::IAM::Role 178 | Properties: 179 | RoleName: !Sub ${ProjectName}-codepipeline-role 180 | AssumeRolePolicyDocument: 181 | Version: 2012-10-17 182 | Statement: 183 | - 184 | Effect: Allow 185 | Principal: 186 | Service: 187 | - codepipeline.amazonaws.com 188 | Action: 189 | - sts:AssumeRole 190 | Path: / 191 | 192 | PipelinePolicy: 193 | Type: AWS::IAM::Policy 194 | DependsOn: S3BucketPolicy 195 | Properties: 196 | PolicyName: !Sub ${ProjectName}-codepipeline-policy 197 | PolicyDocument: 198 | Version: 2012-10-17 199 | Statement: 200 | - 201 | Effect: Allow 202 | Action: 203 | - codepipeline:* 204 | - iam:ListRoles 205 | - cloudformation:Describe* 206 | - cloudFormation:List* 207 | - codecommit:List* 208 | - codecommit:Get* 209 | - codecommit:GitPull 210 | - codecommit:UploadArchive 211 | - codecommit:CancelUploadArchive 212 | - codebuild:BatchGetBuilds 213 | - codebuild:StartBuild 214 | - cloudformation:CreateStack 215 | - cloudformation:DeleteStack 216 | - cloudformation:DescribeStacks 217 | - cloudformation:UpdateStack 218 | - cloudformation:CreateChangeSet 219 | - cloudformation:DeleteChangeSet 220 | - cloudformation:DescribeChangeSet 221 | - cloudformation:ExecuteChangeSet 222 | - cloudformation:SetStackPolicy 223 | - cloudformation:ValidateTemplate 224 | - iam:PassRole 225 | - s3:ListAllMyBuckets 226 | - s3:GetBucketLocation 227 | Resource: 228 | - "*" 229 | - 230 | Effect: Allow 231 | Action: 232 | - kms:Decrypt 233 | Resource: !Ref CMKARN 234 | - 235 | Effect: Allow 236 | Action: 237 | - s3:PutObject 238 | - s3:GetBucketPolicy 239 | - s3:GetObject 240 | - s3:ListBucket 241 | Resource: 242 | - !Join ['',['arn:aws:s3:::',!Ref S3Bucket, '/*']] 243 | - !Join ['',['arn:aws:s3:::',!Ref S3Bucket]] 244 | - 245 | Effect: Allow 246 | Action: 247 | - sts:AssumeRole 248 | Resource: 249 | - !Sub arn:aws:iam::${DevAccount}:role/ToolsAcctCodePipelineCodeCommitRole 250 | - !Sub arn:aws:iam::${ProductionAccount}:role/ToolsAcctCodePipelineCloudFormationRole 251 | - !Sub arn:aws:iam::${TestAccount}:role/ToolsAcctCodePipelineCloudFormationRole 252 | 253 | Roles: 254 | - !Ref PipeLineRole 255 | 256 | Pipeline: 257 | Type: AWS::CodePipeline::Pipeline 258 | Properties: 259 | RoleArn: !GetAtt PipeLineRole.Arn 260 | Name: !Ref AWS::StackName 261 | Stages: 262 | - Name: Source 263 | Actions: 264 | - Name: App 265 | ActionTypeId: 266 | Category: Source 267 | Owner: AWS 268 | Version: 1 269 | Provider: CodeCommit 270 | Configuration: 271 | RepositoryName: !Ref ProjectName 272 | BranchName: master 273 | OutputArtifacts: 274 | - Name: SCCheckoutArtifact 275 | RunOrder: 1 276 | RoleArn: 277 | Fn::If: 278 | - AddCodeBuildResource 279 | - !Sub arn:aws:iam::${DevAccount}:role/ToolsAcctCodePipelineCodeCommitRole 280 | - !Ref AWS::NoValue 281 | - Name: Build 282 | Actions: 283 | - Name: Build 284 | ActionTypeId: 285 | Category: Build 286 | Owner: AWS 287 | Version: 1 288 | Provider: CodeBuild 289 | Configuration: 290 | ProjectName: !Ref BuildProject 291 | RunOrder: 1 292 | InputArtifacts: 293 | - Name: SCCheckoutArtifact 294 | OutputArtifacts: 295 | - Name: BuildOutput 296 | 297 | - Name: Test 298 | Actions: 299 | - Name: RunUnitTests 300 | ActionTypeId: 301 | Category: Test 302 | Owner: AWS 303 | Version: 1 304 | Provider: CodeBuild 305 | Configuration: 306 | ProjectName: !Ref TestProject 307 | InputArtifacts: 308 | - Name: BuildOutput 309 | 310 | - Name: DeployToTest 311 | Actions: 312 | - Name: CreateChangeSetTest 313 | ActionTypeId: 314 | Category: Deploy 315 | Owner: AWS 316 | Version: 1 317 | Provider: CloudFormation 318 | Configuration: 319 | ChangeSetName: sample-lambda-dev 320 | ActionMode: CHANGE_SET_REPLACE 321 | StackName: sample-lambda-dev 322 | Capabilities: CAPABILITY_NAMED_IAM 323 | TemplatePath: BuildOutput::samtemplate.yaml 324 | RoleArn: 325 | Fn::If: 326 | - AddCodeBuildResource 327 | - !Sub arn:aws:iam::${TestAccount}:role/cloudformationdeployer-role 328 | - !Ref AWS::NoValue 329 | InputArtifacts: 330 | - Name: BuildOutput 331 | RunOrder: 1 332 | RoleArn: 333 | Fn::If: 334 | - AddCodeBuildResource 335 | - !Sub arn:aws:iam::${TestAccount}:role/ToolsAcctCodePipelineCloudFormationRole 336 | - !Ref AWS::NoValue 337 | - Name: DeployChangeSetTest 338 | ActionTypeId: 339 | Category: Deploy 340 | Owner: AWS 341 | Version: 1 342 | Provider: CloudFormation 343 | Configuration: 344 | ChangeSetName: sample-lambda-dev 345 | ActionMode: CHANGE_SET_EXECUTE 346 | StackName: sample-lambda-dev 347 | RoleArn: 348 | Fn::If: 349 | - AddCodeBuildResource 350 | - !Sub arn:aws:iam::${TestAccount}:role/cloudformationdeployer-role 351 | - !Ref AWS::NoValue 352 | InputArtifacts: 353 | - Name: BuildOutput 354 | RunOrder: 2 355 | RoleArn: 356 | Fn::If: 357 | - AddCodeBuildResource 358 | - !Sub arn:aws:iam::${TestAccount}:role/ToolsAcctCodePipelineCloudFormationRole 359 | - !Ref AWS::NoValue 360 | - Name: DeployToProduction 361 | Actions: 362 | - Name: CreateChangeSetProd 363 | ActionTypeId: 364 | Category: Deploy 365 | Owner: AWS 366 | Version: 1 367 | Provider: CloudFormation 368 | Configuration: 369 | ChangeSetName: sample-lambda-test 370 | ActionMode: CHANGE_SET_REPLACE 371 | StackName: sample-lambda-test 372 | Capabilities: CAPABILITY_NAMED_IAM 373 | TemplatePath: BuildOutput::samtemplate.yaml 374 | RoleArn: 375 | Fn::If: 376 | - AddCodeBuildResource 377 | - !Sub arn:aws:iam::${ProductionAccount}:role/cloudformationdeployer-role 378 | - !Ref AWS::NoValue 379 | InputArtifacts: 380 | - Name: BuildOutput 381 | RunOrder: 1 382 | RoleArn: 383 | Fn::If: 384 | - AddCodeBuildResource 385 | - !Sub arn:aws:iam::${ProductionAccount}:role/ToolsAcctCodePipelineCloudFormationRole 386 | - !Ref AWS::NoValue 387 | - Name: DeployChangeSetProd 388 | ActionTypeId: 389 | Category: Deploy 390 | Owner: AWS 391 | Version: 1 392 | Provider: CloudFormation 393 | Configuration: 394 | ChangeSetName: sample-lambda-test 395 | ActionMode: CHANGE_SET_EXECUTE 396 | StackName: sample-lambda-test 397 | RoleArn: 398 | Fn::If: 399 | - AddCodeBuildResource 400 | - !Sub arn:aws:iam::${ProductionAccount}:role/cloudformationdeployer-role 401 | - !Ref AWS::NoValue 402 | InputArtifacts: 403 | - Name: BuildOutput 404 | RunOrder: 2 405 | RoleArn: 406 | Fn::If: 407 | - AddCodeBuildResource 408 | - !Sub arn:aws:iam::${ProductionAccount}:role/ToolsAcctCodePipelineCloudFormationRole 409 | - !Ref AWS::NoValue 410 | 411 | ArtifactStore: 412 | Type: S3 413 | Location: !Ref S3Bucket 414 | EncryptionKey: 415 | Id: !Ref CMKARN 416 | Type: KMS 417 | S3BucketPolicy: 418 | Type: AWS::S3::BucketPolicy 419 | Properties: 420 | Bucket: !Ref S3Bucket 421 | PolicyDocument: 422 | Statement: 423 | - 424 | Action: 425 | - s3:* 426 | Effect: Allow 427 | Resource: 428 | - !Sub arn:aws:s3:::${S3Bucket} 429 | - !Sub arn:aws:s3:::${S3Bucket}/* 430 | Principal: 431 | AWS: 432 | - !Sub arn:aws:iam::${DevAccount}:role/ToolsAcctCodePipelineCodeCommitRole 433 | - !Sub arn:aws:iam::${TestAccount}:role/ToolsAcctCodePipelineCloudFormationRole 434 | - !Sub arn:aws:iam::${TestAccount}:role/cloudformationdeployer-role 435 | - !Sub arn:aws:iam::${ProductionAccount}:role/ToolsAcctCodePipelineCloudFormationRole 436 | - !Sub arn:aws:iam::${ProductionAccount}:role/cloudformationdeployer-role 437 | - !GetAtt [BuildProjectRole,Arn] 438 | -------------------------------------------------------------------------------- /Pipeline/ToolsAcct/pre-reqs.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 3 | # the License. A copy of the License is located at 4 | # http://aws.amazon.com/apache2.0/ 5 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 6 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 7 | # limitations under the License. 8 | 9 | AWSTemplateFormatVersion: '2010-09-09' 10 | Description: Creates a CMK in KMS and grants access to other accounts 11 | Parameters: 12 | DevAccount: 13 | Description: AWS AccountNumber for dev 14 | Type: Number 15 | TestAccount: 16 | Description: AWS AccountNumber for test 17 | Type: Number 18 | ProductionAccount: 19 | Description: AWS AccountNumber for production 20 | Type: Number 21 | ProjectName: 22 | Description: Name of the Project 23 | Type: String 24 | Default: sample-lambda 25 | CodeBuildCondition: 26 | Description: Conditionally adds the access required by code build project role 27 | Type: String 28 | Default: false 29 | Conditions: 30 | AddCodeBuildResource: !Equals [ !Ref CodeBuildCondition, true ] 31 | Resources: 32 | KMSKey: 33 | Type: AWS::KMS::Key 34 | Properties: 35 | Description: Used by Assumed Roles in Dev/Test/Prod accounts to Encrypt/Decrypt code 36 | EnableKeyRotation: true 37 | KeyPolicy: 38 | Version: "2012-10-17" 39 | Id: !Ref AWS::StackName 40 | Statement: 41 | - 42 | Sid: Allows admin of the key 43 | Effect: Allow 44 | Principal: 45 | AWS: !Sub arn:aws:iam::${AWS::AccountId}:root 46 | Action: 47 | - "kms:Create*" 48 | - "kms:Describe*" 49 | - "kms:Enable*" 50 | - "kms:List*" 51 | - "kms:Put*" 52 | - "kms:Update*" 53 | - "kms:Revoke*" 54 | - "kms:Disable*" 55 | - "kms:Get*" 56 | - "kms:Delete*" 57 | - "kms:ScheduleKeyDeletion" 58 | - "kms:CancelKeyDeletion" 59 | Resource: "*" 60 | - 61 | Sid: Allow use of the key for CryptoGraphy Lambda 62 | Effect: Allow 63 | Principal: 64 | AWS: 65 | - !Sub arn:aws:iam::${ProductionAccount}:root 66 | - !Sub arn:aws:iam::${TestAccount}:root 67 | - !Sub arn:aws:iam::${DevAccount}:root 68 | - !If 69 | - AddCodeBuildResource 70 | - !Sub arn:aws:iam::${AWS::AccountId}:role/${ProjectName}-CodeBuildRole 71 | - !Ref AWS::NoValue 72 | Action: 73 | - kms:Encrypt 74 | - kms:Decrypt 75 | - kms:ReEncrypt* 76 | - kms:GenerateDataKey* 77 | - kms:DescribeKey 78 | Resource: "*" 79 | KMSAlias: 80 | Type: AWS::KMS::Alias 81 | Properties: 82 | AliasName: !Sub alias/codepipeline-crossaccounts 83 | TargetKeyId: !Ref KMSKey 84 | ArtifactBucket: 85 | Type: AWS::S3::Bucket 86 | DeletionPolicy: Retain 87 | 88 | Outputs: 89 | CMK: 90 | Value: !GetAtt [KMSKey,Arn] 91 | ArtifactBucket: 92 | Value: !Ref ArtifactBucket 93 | 94 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cross Account AWS CodePipeline for IAM Policy Tester 2 | 3 | This repository accompanies the [IAM Policy Tester Pipeline](https://aws.amazon.com/blogs/devops/unit-testing-iam-policies-across-multiple-accounts/) blogpost. 4 | It contains an example of a secure, cross-account, continous delivery [CodePipeline](https://aws.amazon.com/blogs/devops/aws-building-a-secure-cross-account-continuous-delivery-pipeline/). This pipeline demonstrates the unit testing of an IAM policy to validate permissions in different AWS Accounts. 5 | 6 | The same resource, with the same IAM policy attached may not be able authorised for certain actions in an account. External policies, such as SCP's can limit the actions of a resource, despite the IAM policy associated with a resource. 7 | 8 | Such conflicts can occur when crossing the boundry from development accounts to production-like accounts that contain further restrictions. 9 | This pipeline demonstrates how this problem can be detected using `iam policy simulator` to validate if an IAM policy and action is permitted within an account. 10 | 11 | 12 | ## Running the example 13 | 14 | #### 1. Clone this repository 15 | 16 | [Clone](https://help.github.com/articles/cloning-a-repository/) the [AWS Policy Tester Pipeline](https://github.com/aws-samples/iam-policy-tester-pipeline) repository. From your terminal application, execute the following command: 17 | 18 | ```console 19 | git clone https://github.com/aws-samples/iam-policy-tester-pipeline 20 | ``` 21 | 22 | This creates a directory named `iam-policy-tester-pipeline` in your current directory. 23 | 24 | 25 | #### 2. Create **AWS CodeCommit** repository in Development Account 26 | 27 | Follow the [instructions here](http://docs.aws.amazon.com/codecommit/latest/userguide/getting-started.html#getting-started-create-repo) to create a CodeCommit repository in the Development Account. Name your repository as sample-lambda. Alternatively, from your terminal application, execute the following command. 28 | 29 | ```console 30 | aws codecommit create-repository --repository-name sample-lambda --repository-description "Sample Lambda Function" 31 | ``` 32 | 33 | Note the `cloneUrlHttp` URL in the response from above CLI. 34 | 35 | You may refer [here](http://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html#how-to-create-repository-cli) 36 | on further details, in order to setup AWS Cli , if required. 37 | 38 | #### 3. Add a new remote 39 | 40 | From your terminal application, within the `SampleLambda` directory, execute the following command: 41 | 42 | ```console 43 | git init && git remote add AWSCodeCommit HTTP_CLONE_URL_FROM_STEP_2 44 | ``` 45 | 46 | Follow the instructions [here](http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up.html) for local git setup required to push code to CodeCommit repository. 47 | 48 | #### 4. Replace the Policy Source ARN 49 | 50 | You need to specify the user, group, or role whose policies you want to include in the simulation. To do this, within the `SampleLambda` directory, modify the value in `scripts/source.txt` file. 51 | 52 | #### 5. Push the code AWS CodeCommit 53 | 54 | From your terminal application, execute the following commands: 55 | 56 | ```console 57 | git add * 58 | git commit -am "Initialise the SampleLambda repository" 59 | git push AWSCodeCommit master 60 | ``` 61 | 62 | #### 6. Run the script to generate the Cross Account Pipeline 63 | 64 | From your terminal application, back in the `iam-policy-tester-pipeline` directory, execute the following command: 65 | 66 | ```console 67 | chmod +x single-click-cross-account-pipeline.sh && ./single-click-cross-account-pipeline.sh 68 | ``` 69 | 70 | This last step deploys the entire pipeline. It expects to receive the account numbers to which it will deploy the reference architecture. It creates Amazon S3 buckets for the build artifacts and encryption keys for secure cross-account communication, and sets up CodePipeline, CodeBuild, and CodeDeploy in the account structure described above. After this step, each update in the sample-lambda repository triggers an execution of the pipeline. You can manually release a change in the pipeline after deploying it to ensure it is working. 71 | 72 | ## License 73 | 74 | This sample code is made available under the Apache 2.0 License. See the LICENSE file. 75 | -------------------------------------------------------------------------------- /SampleLambda/README.md: -------------------------------------------------------------------------------- 1 | # Sample Lambda 2 | 3 | A Lambda function that returns the current time. 4 | 5 | It is defined in `lambda-cloudformation.yaml` 6 | 7 | ## Deployment 8 | 9 | This sample lambda is intended to be deployed as part of the encompassing sample. -------------------------------------------------------------------------------- /SampleLambda/lambda-cloudformation.yaml: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 3 | # the License. A copy of the License is located at 4 | # http://aws.amazon.com/apache2.0/ 5 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 6 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 7 | # limitations under the License. 8 | 9 | AWSTemplateFormatVersion: '2010-09-09' 10 | Transform: AWS::Serverless-2016-10-31 11 | Description: Outputs the time 12 | Resources: 13 | TimeFunction: 14 | Type: AWS::Serverless::Function 15 | Properties: 16 | Handler: index.handler 17 | Runtime: python3.7 18 | CodeUri: ./scripts 19 | Events: 20 | MyTimeApi: 21 | Type: Api 22 | Properties: 23 | Path: /TimeResource 24 | Method: GET 25 | -------------------------------------------------------------------------------- /SampleLambda/scripts/__pycache__/test_module.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/iam-policy-tester-pipeline/3092d9873e6a7c9e181d27149844386e388399b5/SampleLambda/scripts/__pycache__/test_module.cpython-37.pyc -------------------------------------------------------------------------------- /SampleLambda/scripts/actions.json: -------------------------------------------------------------------------------- 1 | [ 2 | "s3:ListBucket" 3 | ] -------------------------------------------------------------------------------- /SampleLambda/scripts/iam_policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "s3:ListBucket" 8 | ], 9 | "Resource": "*" 10 | } 11 | ] 12 | } -------------------------------------------------------------------------------- /SampleLambda/scripts/index.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 3 | # the License. A copy of the License is located at 4 | # http://aws.amazon.com/apache2.0/ 5 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 6 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 7 | # limitations under the License. 8 | 9 | from datetime import datetime 10 | 11 | def handler(event, context): 12 | dateTimeObj = datetime.now() 13 | message = 'The time in London is: ' + str(dateTimeObj) 14 | return { 15 | 'headers': { 16 | 'Content-Type': "text/plain" 17 | }, 18 | 'statusCode': 200, 19 | 'body' : message 20 | } 21 | -------------------------------------------------------------------------------- /SampleLambda/scripts/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | botocore 3 | pyyaml -------------------------------------------------------------------------------- /SampleLambda/scripts/source.txt: -------------------------------------------------------------------------------- 1 | arn:aws:iam::123456789:user/admin 2 | -------------------------------------------------------------------------------- /SampleLambda/scripts/test_module.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 3 | # the License. A copy of the License is located at 4 | # http://aws.amazon.com/apache2.0/ 5 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 6 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 7 | # limitations under the License. 8 | 9 | import unittest 10 | import json 11 | import boto3 12 | 13 | 14 | class TestPolicies(unittest.TestCase): 15 | def test_policy(self): 16 | policy = readFile("iam_policy.json") 17 | actions = json.loads(readFile("actions.json")) 18 | source = readFile("source.txt") 19 | 20 | evaluation_results = simulatePrincipalPolicy(source, actions, [policy]) 21 | failed = [x for x in evaluation_results if isDenied(x)] 22 | if len(failed) > 0: 23 | self.fail("Some actions were denied\n" + prettyPrintResults(failed)) 24 | 25 | 26 | def readFile(file_name): 27 | with open(file_name, "r") as f: 28 | read_data = f.read() 29 | return read_data 30 | 31 | 32 | def simulateCustomPolicy(actions, policies): 33 | """Simulate a set of actions against a custom policy""" 34 | client = boto3.client("iam") 35 | response = client.simulate_custom_policy( 36 | PolicyInputList=policies, ActionNames=actions 37 | ) 38 | return response["EvaluationResults"] 39 | 40 | def simulatePrincipalPolicy(source, actions, policies): 41 | """Simulate a set of actions from a specific principal against a custom policy""" 42 | client = boto3.client("iam") 43 | response = client.simulate_principal_policy( 44 | PolicySourceArn=source, PolicyInputList=policies, ActionNames=actions 45 | ) 46 | return response["EvaluationResults"] 47 | 48 | def isDenied(evaluationResults): 49 | return evaluationResults["EvalDecision"] != "allowed" 50 | 51 | 52 | def prettyPrintResults(evaluationResults): 53 | """prettyPrintResults returns a string formatting the results of a simulation evaluation result""" 54 | output = "" 55 | for er in evaluationResults: 56 | message = ( 57 | f"Evaluated Action Name: {er['EvalActionName']}\n" 58 | f"\tEvaluated Resource name: {er['EvalResourceName']}\n" 59 | f"\tDecision: {er['EvalDecision']}\n" 60 | ) 61 | output += message 62 | return output 63 | 64 | 65 | if __name__ == "__main__": 66 | unittest.main() 67 | -------------------------------------------------------------------------------- /single-click-cross-account-pipeline.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with 5 | # the License. A copy of the License is located at 6 | # http://aws.amazon.com/apache2.0/ 7 | # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 8 | # CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and 9 | # limitations under the License. 10 | 11 | echo -n "Enter ToolsAccount > " 12 | read ToolsAccount 13 | 14 | echo -n "Enter ToolsAccount ProfileName for AWS Cli operations> " 15 | read ToolsAccountProfile 16 | 17 | echo -n "Enter Dev Account > " 18 | read DevAccount 19 | 20 | echo -n "Enter DevAccount ProfileName for AWS Cli operations> " 21 | read DevAccountProfile 22 | 23 | echo -n "Enter Test Account > " 24 | read TestAccount 25 | 26 | echo -n "Enter TestAccount ProfileName for AWS Cli operations> " 27 | read TestAccountProfile 28 | 29 | echo -n "Enter Prod Account > " 30 | read ProdAccount 31 | 32 | echo -n "Enter ProdAccount ProfileName for AWS Cli operations> " 33 | read ProdAccountProfile 34 | 35 | 36 | aws cloudformation deploy --stack-name pre-reqs --template-file Pipeline/ToolsAcct/pre-reqs.yaml --parameter-overrides DevAccount=$DevAccount TestAccount=$TestAccount ProductionAccount=$ProdAccount --profile $ToolsAccountProfile 37 | echo -n "Enter S3 Bucket created from above > " 38 | read S3Bucket 39 | 40 | echo -n "Enter CMK ARN created from above > " 41 | read CMKArn 42 | 43 | echo -n "Executing in DEV Account" 44 | aws cloudformation deploy --stack-name toolsacct-codepipeline-role --template-file Pipeline/DevAccount/toolsacct-codepipeline-codecommit.yaml --capabilities CAPABILITY_NAMED_IAM --parameter-overrides ToolsAccount=$ToolsAccount CMKARN=$CMKArn --profile $DevAccountProfile 45 | 46 | echo -n "Executing in TEST Account" 47 | aws cloudformation deploy --stack-name toolsacct-codepipeline-cloudformation-role --template-file Pipeline/TestAccount/toolsacct-codepipeline-cloudformation-deployer.yaml --capabilities CAPABILITY_NAMED_IAM --parameter-overrides ToolsAccount=$ToolsAccount CMKARN=$CMKArn S3Bucket=$S3Bucket --profile $TestAccountProfile 48 | 49 | echo -n "Executing in PROD Account" 50 | aws cloudformation deploy --stack-name toolsacct-codepipeline-cloudformation-role --template-file Pipeline/TestAccount/toolsacct-codepipeline-cloudformation-deployer.yaml --capabilities CAPABILITY_NAMED_IAM --parameter-overrides ToolsAccount=$ToolsAccount CMKARN=$CMKArn S3Bucket=$S3Bucket --profile $ProdAccountProfile 51 | 52 | 53 | echo -n "Creating Pipeline in Tools Account" 54 | aws cloudformation deploy --stack-name sample-lambda-pipeline --template-file Pipeline/ToolsAcct/code-pipeline.yaml --parameter-overrides DevAccount=$DevAccount TestAccount=$TestAccount ProductionAccount=$ProdAccount CMKARN=$CMKArn S3Bucket=$S3Bucket --capabilities CAPABILITY_NAMED_IAM --profile $ToolsAccountProfile 55 | 56 | echo -n "Adding Permissions to the CMK" 57 | aws cloudformation deploy --stack-name pre-reqs --template-file Pipeline/ToolsAcct/pre-reqs.yaml --parameter-overrides CodeBuildCondition=true --profile $ToolsAccountProfile 58 | 59 | echo -n "Adding Permissions to the Cross Accounts" 60 | aws cloudformation deploy --stack-name sample-lambda-pipeline --template-file Pipeline/ToolsAcct/code-pipeline.yaml --parameter-overrides CrossAccountCondition=true --capabilities CAPABILITY_NAMED_IAM --profile $ToolsAccountProfile 61 | --------------------------------------------------------------------------------