├── .gitignore ├── LICENSE ├── README.md ├── ami_builder_event.json ├── ansible ├── playbook.yaml ├── requirements.yaml └── roles │ └── common │ └── tasks │ └── main.yaml ├── buildspec.yml ├── cloudformation └── pipeline.yaml ├── images ├── ami-builder-diagram.png ├── ami-builder-initial-pipeline.png ├── ami-builder-pipeline.png ├── build_phases.png ├── create_policy.png ├── create_project.png ├── deploy-to-aws.png └── new_build.png └── packer_cis.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/osx,linux,windows 2 | 3 | ### Linux ### 4 | *~ 5 | 6 | # temporary files which can be created if a process still has a handle open of a deleted file 7 | .fuse_hidden* 8 | 9 | # KDE directory preferences 10 | .directory 11 | 12 | # Linux trash folder which might appear on any partition or disk 13 | .Trash-* 14 | 15 | # .nfs files are created when an open file is removed but is still being accessed 16 | .nfs* 17 | 18 | ### OSX ### 19 | *.DS_Store 20 | .AppleDouble 21 | .LSOverride 22 | 23 | # Icon must end with two \r 24 | Icon 25 | 26 | # Thumbnails 27 | ._* 28 | 29 | # Files that might appear in the root of a volume 30 | .DocumentRevisions-V100 31 | .fseventsd 32 | .Spotlight-V100 33 | .TemporaryItems 34 | .Trashes 35 | .VolumeIcon.icns 36 | .com.apple.timemachine.donotpresent 37 | 38 | # Directories potentially created on remote AFP share 39 | .AppleDB 40 | .AppleDesktop 41 | Network Trash Folder 42 | Temporary Items 43 | .apdisk 44 | 45 | ### Windows ### 46 | # Windows thumbnail cache files 47 | Thumbs.db 48 | ehthumbs.db 49 | ehthumbs_vista.db 50 | 51 | # Folder config file 52 | Desktop.ini 53 | 54 | # Recycle Bin used on file shares 55 | $RECYCLE.BIN/ 56 | 57 | # Windows Installer files 58 | *.cab 59 | *.msi 60 | *.msm 61 | *.msp 62 | 63 | # Windows shortcuts 64 | *.lnk 65 | 66 | 67 | # End of https://www.gitignore.io/api/osx,linux,windows 68 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | This Packer AMI Builder creates a new AMI out of the latest Amazon Linux AMI, and also provides a cloudformation template that leverages AWS CodePipeline to 4 | orchestrate the entire process. 5 | 6 | ![Packer AMI Builder Diagram](images/ami-builder-diagram.png) 7 | 8 | ## Source code structure 9 | 10 | ```bash 11 | ├── ansible 12 | │   ├── playbook.yaml <-- Ansible playbook file 13 | │   ├── requirements.yaml <-- Ansible Galaxy requirements containing additional Roles to be used (CIS, Cloudwatch Logs) 14 | │   └── roles 15 | │   ├── common <-- Upgrades all packages through ``yum`` 16 | ├── buildspec.yml <-- CodeBuild spec 17 | ├── cloudformation <-- Cloudformation to create entire pipeline 18 | │   └── pipeline.yaml 19 | ├── packer_cis.json <-- Packer template for Pipeline 20 | ``` 21 | 22 | 23 | ## Cloudformation template 24 | 25 | Cloudformation will create the following resources as part of the AMI Builder for Packer: 26 | 27 | * ``cloudformation/pipeline.yaml`` 28 | + AWS CodeCommit - Git repository 29 | + AWS CodeBuild - Downloads Packer and run Packer to build AMI 30 | + AWS CodePipeline - Orchestrates pipeline and listen for new commits in CodeCommit 31 | + Amazon SNS Topic - AMI Builds Notification via subscribed email 32 | + Amazon Cloudwatch Events Rule - Custom Event for AMI Builder that will trigger SNS upon AMI completion 33 | 34 | 35 | ## HOWTO 36 | 37 | **Before you start** 38 | 39 | * Install [GIT](https://git-scm.com/downloads) if you don't have it 40 | * Make sure AWS CLI is configured properly 41 | * [Configured AWS CLI and Git](http://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-https-unixes.html) to connect to AWS CodeCommit repositories 42 | 43 | **Launch the Cloudformation stack** 44 | 45 | Region | AMI Builder Launch Template 46 | ------------------------------------------------- | --------------------------------------------------------------------------------- 47 | N. Virginia (us-east-1) | [![Launch Stack](images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/new?stackName=AMI-Builder-Blogpost&templateURL=https://s3-eu-west-1.amazonaws.com/ami-builder-packer/cloudformation/pipeline.yaml) 48 | Ireland (eu-west-1) | [![Launch Stack](images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-1#/stacks/new?stackName=AMI-Builder-Blogpost&templateURL=https://s3-eu-west-1.amazonaws.com/ami-builder-packer/cloudformation/pipeline.yaml) 49 | London (eu-west-2) | [![Launch Stack](images/deploy-to-aws.png)](https://console.aws.amazon.com/cloudformation/home?region=eu-west-2#/stacks/new?stackName=AMI-Builder-Blogpost&templateURL=https://s3-eu-west-1.amazonaws.com/ami-builder-packer/cloudformation/pipeline.yaml) 50 | 51 | **To clone the AWS CodeCommit repository (console)** 52 | 53 | 1. From the AWS Management Console, open the AWS CloudFormation console. 54 | 2. Choose the AMI-Builder-Blogpost stack, and then choose Output. 55 | 3. Make a note of the Git repository URL. 56 | 4. Use git to clone the repository. 57 | For example: git clone https://git-codecommit.eu-west-1.amazonaws.com/v1/repos/AMI-Builder_repo 58 | 59 | **To clone the AWS CodeCommit repository (CLI)** 60 | 61 | ```bash 62 | # Retrieve CodeCommit repo URL 63 | git_repo=$(aws cloudformation describe-stacks --query 'Stacks[0].Outputs[?OutputKey==`GitRepository`].OutputValue' --output text --stack-name "AMI-Builder-Blogpost") 64 | 65 | # Clone repository locally 66 | git clone ${git_repo} 67 | ``` 68 | 69 | Next, we need to copy all files in this repository into the newly cloned Git repository: 70 | 71 | * Download [ami-builder-packer ZIP](https://github.com/awslabs/ami-builder-packer/archive/master.zip). 72 | * Extract and copy the contents to the Git repo 73 | 74 | Lastly, commit these changes to your AWS CodeCommit repo and watch the AMI being built through the AWS CodePipeline Console: 75 | 76 | ```bash 77 | git add . 78 | git commit -m "SHIP THIS AMI" 79 | git push origin master 80 | ``` 81 | 82 | ![AWS CodePipeline Console - AMI Builder Pipeline](images/ami-builder-pipeline.png) 83 | 84 | ## Known issues 85 | 86 | * ~~Currently, Packer doesn't work with ECS IAM Roles (also used by CodeBuild)~~ 87 | - ~~That's why we build a credentials file that leverages temporary credentials in the ``buildspec``~~ 88 | - ~~When Packer supports this feature, this will no longer be necessary~~ 89 | * If Build process fails and within AWS CodeBuild Build logs you find the following line ``Timeout waiting for SSH.``, it means either 90 | - A) You haven't chosen a VPC Public Subnet, and therefore Packer cannot connect to the instance 91 | - B) There may have been a connectivity issue between Packer and EC2; retrying the build step within AWS CodePipeline should work just fine 92 | 93 | -------------------------------------------------------------------------------- /ami_builder_event.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "Source": "com.ami.builder", 4 | "DetailType": "AmiBuilder", 5 | "Detail": "{ \"AmiStatus\": \"Created\"}", 6 | "Resources": [ "<>" ] 7 | } 8 | ] 9 | -------------------------------------------------------------------------------- /ansible/playbook.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - hosts: localhost 3 | connection: local 4 | gather_facts: true # gather OS info that is made available for tasks/roles 5 | become: yes # majority of CIS tasks require root 6 | vars: 7 | # CIS Controls whitepaper: http://bit.ly/2mGAmUc 8 | # AWS CIS Whitepaper: http://bit.ly/2m2Ovrh 9 | cis_level_1_exclusions: 10 | # 3.4.2, 3.4.3 and 3.6.2 effectively blocks access to all ports to the machine 11 | ## This can break automation; ignoring it as there are stronger mechanisms than that 12 | - 3.4.2 13 | - 3.4.3 14 | - 3.6.2 15 | # Cloudwatch Logs will be used instead of Rsyslog/Syslog-ng 16 | ## Same would be true if any other software that doesn't support Rsyslog/Syslog-ng mechanisms 17 | - 4.2.1.4 18 | - 4.2.2.4 19 | - 4.2.2.5 20 | # Autofs is no longer installed and we need to ignore it or else will fail 21 | - 1.1.19 22 | # Password reuse limit task fails due to AttributionError in Ansible code; skipping 23 | - 5.3.3 24 | # Cloudwatch Logs Role configuration 25 | logs: 26 | - file: /var/log/messages 27 | group_name: "system_logs" 28 | roles: 29 | - common 30 | - anthcourtney.cis-amazon-linux 31 | # - dharrisio.aws-cloudwatch-logs-agent 32 | -------------------------------------------------------------------------------- /ansible/requirements.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | - src: anthcourtney.cis-amazon-linux 3 | - src: dharrisio.aws-cloudwatch-logs-agent 4 | -------------------------------------------------------------------------------- /ansible/roles/common/tasks/main.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | # Ensure all packages have been patched 4 | - name: upgrade all packages 5 | yum: 6 | name: "*" 7 | state: latest 8 | -------------------------------------------------------------------------------- /buildspec.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | 3 | phases: 4 | pre_build: 5 | commands: 6 | - echo "Installing Packer" 7 | - curl -o packer.zip https://releases.hashicorp.com/packer/1.3.3/packer_1.3.3_linux_amd64.zip && unzip packer.zip 8 | - echo "Validating Packer template" 9 | - ./packer validate packer_cis.json 10 | build: 11 | commands: 12 | - ./packer build -color=false packer_cis.json | tee build.log 13 | post_build: 14 | commands: 15 | - egrep "${AWS_REGION}\:\sami\-" build.log | cut -d' ' -f2 > ami_id.txt 16 | # Packer doesn't return non-zero status; we must do that if Packer build failed 17 | - test -s ami_id.txt || exit 1 18 | - sed -i.bak "s/<>/$(cat ami_id.txt)/g" ami_builder_event.json 19 | - aws events put-events --entries file://ami_builder_event.json 20 | - echo "build completed on `date`" 21 | artifacts: 22 | files: 23 | - ami_builder_event.json 24 | - build.log 25 | discard-paths: yes 26 | -------------------------------------------------------------------------------- /cloudformation/pipeline.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Parameters: 3 | 4 | ServiceName: 5 | Type: String 6 | Default: AMI-Builder 7 | Description: Name for this service; used in the code repository and pipeline names 8 | 9 | CodeBuildEnvironment: 10 | Type: String 11 | Default: "eb-python-2.6-amazonlinux-64:2.1.6" 12 | Description: Docker image to use for CodeBuild container - Use http://amzn.to/2mjCI91 for reference 13 | 14 | BuilderVPC: 15 | Type: AWS::EC2::VPC::Id 16 | Description: VPC ID that AMI Builder will use to launch temporary resource 17 | 18 | BuilderPublicSubnet: 19 | Type: AWS::EC2::Subnet::Id 20 | Description: Public Subnet ID that AMI Builder will use to launch temporary resource 21 | 22 | NotificationEmailAddress: 23 | Type: String 24 | Description: Email to receive new AMI ID created by AMI Builder 25 | 26 | Metadata: 27 | AWS::CloudFormation::Interface: 28 | ParameterGroups: 29 | - 30 | Label: 31 | default: "AMI Builder - Resources Name" 32 | Parameters: 33 | - ServiceName 34 | - 35 | Label: 36 | default: "Packer - Temporary Resources" 37 | Parameters: 38 | - BuilderVPC 39 | - BuilderPublicSubnet 40 | - 41 | Label: 42 | default: "Packer - CodeBuild environment" 43 | Parameters: 44 | - CodeBuildEnvironment 45 | - 46 | Label: 47 | default: "AMI Builder - Notifications" 48 | Parameters: 49 | - NotificationEmailAddress 50 | ParameterLabels: 51 | ServiceName: 52 | default: "CodeCommit repo and Pipeline name?" 53 | BuilderVPC: 54 | default: "Which VPC should I use?" 55 | BuilderPublicSubnet: 56 | default: "Which Public Subnet should I use?" 57 | CodeBuildEnvironment: 58 | default: "Should I use a different Docker Image?" 59 | NotificationEmailAddress: 60 | default: "Who should I notify upon completion?" 61 | 62 | 63 | Resources: 64 | 65 | ########## 66 | # Source # 67 | ########## 68 | 69 | # Code repository for AMI Builder 70 | CodeRepository: 71 | Type: AWS::CodeCommit::Repository 72 | Properties: 73 | RepositoryName: !Sub '${ServiceName}_repo' 74 | RepositoryDescription: !Sub 'Repository for ${ServiceName} service' 75 | 76 | 77 | ######### 78 | # Build # 79 | ######### 80 | 81 | # S3 Bucket that CodePipeline/CodeBuild service will use 82 | # It will receive both SourceZip (CodeCommit Git HEAD) and BuiltZIP (CodeBuild Artifacts) 83 | BuildArtifactsBucket: 84 | Type: AWS::S3::Bucket 85 | 86 | CodeBuildServiceRole: 87 | Type: AWS::IAM::Role 88 | Properties: 89 | Path: '/managed/' 90 | ManagedPolicyArns: 91 | - 'arn:aws:iam::aws:policy/PowerUserAccess' 92 | AssumeRolePolicyDocument: 93 | Version: '2012-10-17' 94 | Statement: 95 | - 96 | Action: 'sts:AssumeRole' 97 | Effect: Allow 98 | Principal: 99 | Service: 100 | - codebuild.amazonaws.com 101 | Policies: 102 | - 103 | PolicyName: CodeBuildAccess 104 | PolicyDocument: 105 | Version: '2012-10-17' 106 | Statement: 107 | - 108 | Sid: "CodeBuildToCWL" 109 | Effect: Allow 110 | Action: 111 | - 'logs:CreateLogGroup' 112 | - 'logs:CreateLogStream' 113 | - 'logs:PutLogEvents' 114 | Resource: 115 | - !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ServiceName}_build' 116 | - !Sub 'arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/codebuild/${ServiceName}_build:*' 117 | - 118 | Sid: "CodeBuildToS3ArtifactRepo" 119 | Effect: Allow 120 | Action: 121 | - 's3:GetObject' 122 | - 's3:GetObjectVersion' 123 | - 's3:PutObject' 124 | Resource: !Sub 'arn:aws:s3:::${BuildArtifactsBucket}/*' 125 | 126 | 127 | CodeBuildProject: 128 | Type: AWS::CodeBuild::Project 129 | Properties: 130 | Name: !Sub '${ServiceName}_build' 131 | Artifacts: 132 | Type: CODEPIPELINE 133 | Environment: 134 | Type: LINUX_CONTAINER 135 | ComputeType: BUILD_GENERAL1_SMALL 136 | Image: !Sub 'aws/codebuild/${CodeBuildEnvironment}' 137 | EnvironmentVariables: 138 | - Name: BUILD_OUTPUT_BUCKET 139 | Value: !Ref BuildArtifactsBucket 140 | - Name: BUILD_VPC_ID 141 | Value: !Ref BuilderVPC 142 | - Name: BUILD_SUBNET_ID 143 | Value: !Ref BuilderPublicSubnet 144 | ServiceRole: !GetAtt CodeBuildServiceRole.Arn 145 | Source: 146 | Type: CODEPIPELINE 147 | 148 | ############# 149 | # Pipeline # 150 | ############# 151 | 152 | PipelineExecutionRole: 153 | Type: AWS::IAM::Role 154 | Properties: 155 | Path: '/managed/' 156 | AssumeRolePolicyDocument: 157 | Version: '2012-10-17' 158 | Statement: 159 | - 160 | Action: 'sts:AssumeRole' 161 | Effect: Allow 162 | Principal: 163 | Service: 164 | - codepipeline.amazonaws.com 165 | Policies: 166 | - 167 | PolicyName: CodePipelinePassRoleAccess 168 | PolicyDocument: 169 | Version: '2012-10-17' 170 | Statement: 171 | - 172 | Action: 'iam:PassRole' 173 | Effect: Allow 174 | Resource: !GetAtt CodeBuildServiceRole.Arn 175 | - 176 | PolicyName: CodePipelineS3ArtifactAccess 177 | PolicyDocument: 178 | Version: '2012-10-17' 179 | Statement: 180 | - 181 | Action: 182 | - 's3:GetObject' 183 | - 's3:GetObjectVersion' 184 | - 's3:GetBucketVersioning' 185 | - 's3:PutObject' 186 | Effect: Allow 187 | Resource: 188 | - !Sub 'arn:aws:s3:::${BuildArtifactsBucket}' 189 | - !Sub 'arn:aws:s3:::${BuildArtifactsBucket}/*' 190 | - 191 | PolicyName: CodePipelineGitRepoAccess 192 | PolicyDocument: 193 | Version: '2012-10-17' 194 | Statement: 195 | - 196 | Action: 197 | - 'codecommit:GetBranch' 198 | - 'codecommit:GetCommit' 199 | - 'codecommit:UploadArchive' 200 | - 'codecommit:GetUploadArchiveStatus' 201 | - 'codecommit:CancelUploadArchive' 202 | Effect: Allow 203 | Resource: !GetAtt CodeRepository.Arn 204 | - 205 | PolicyName: CodePipelineBuildAccess 206 | PolicyDocument: 207 | Version: '2012-10-17' 208 | Statement: 209 | - 210 | Action: 211 | - 'codebuild:StartBuild' 212 | - 'codebuild:StopBuild' 213 | - 'codebuild:BatchGetBuilds' 214 | Effect: Allow 215 | Resource: !GetAtt CodeBuildProject.Arn 216 | 217 | 218 | Pipeline: 219 | Type: AWS::CodePipeline::Pipeline 220 | Properties: 221 | ArtifactStore: 222 | Location: !Ref BuildArtifactsBucket 223 | Type: S3 224 | Name: !Sub ${ServiceName}_pipeline 225 | RoleArn: !GetAtt PipelineExecutionRole.Arn 226 | Stages: 227 | - 228 | Name: Source 229 | Actions: 230 | - 231 | Name: CodeCommitRepo 232 | ActionTypeId: 233 | Category: Source 234 | Owner: AWS 235 | Provider: CodeCommit 236 | Version: 1 237 | Configuration: 238 | RepositoryName: !Sub '${ServiceName}_repo' 239 | BranchName: master 240 | OutputArtifacts: 241 | - Name: SourceZip 242 | RunOrder: 1 243 | - 244 | Name: Build 245 | Actions: 246 | - 247 | Name: CodeBuild 248 | ActionTypeId: 249 | Category: Build 250 | Owner: AWS 251 | Provider: CodeBuild 252 | Version: 1 253 | Configuration: 254 | ProjectName: !Ref CodeBuildProject 255 | InputArtifacts: 256 | - Name: SourceZip 257 | OutputArtifacts: 258 | - Name: BuiltZip 259 | 260 | ###################### 261 | # AMI Builder Event # 262 | ###################### 263 | 264 | AmiBuilderNotificationTopic: 265 | Type: "AWS::SNS::Topic" 266 | Properties: 267 | Subscription: 268 | - 269 | Endpoint: !Ref NotificationEmailAddress 270 | Protocol: "email" 271 | TopicName: "AmiBuilder-Notify" 272 | 273 | AmiBuilderNotificationTopicPolicy: 274 | Type: AWS::SNS::TopicPolicy 275 | Properties: 276 | PolicyDocument: 277 | Id: AllowCloudwatchEventsToPublish 278 | Version: '2012-10-17' 279 | Statement: 280 | - 281 | Sid: My-statement-id 282 | Effect: Allow 283 | Principal: 284 | Service: "events.amazonaws.com" 285 | Action: sns:Publish 286 | Resource: !Ref AmiBuilderNotificationTopic 287 | Topics: 288 | - !Ref AmiBuilderNotificationTopic 289 | 290 | AmiBuilderCustomEvent: 291 | Type: "AWS::Events::Rule" 292 | Properties: 293 | Description: "AmiBuilder-Complete" 294 | EventPattern: 295 | source: 296 | - "com.ami.builder" 297 | detail-type: 298 | - "AmiBuilder" 299 | detail: 300 | AmiStatus: 301 | - "Created" 302 | State: "ENABLED" 303 | Targets: 304 | - 305 | Id: "NewAMI-Notify" 306 | Arn: !Ref AmiBuilderNotificationTopic 307 | 308 | 309 | Outputs: 310 | 311 | ArtifactRepository: 312 | Description: S3 Bucket for Pipeline and Build Artifacts 313 | Value: !Ref BuildArtifactsBucket 314 | 315 | CodeBuildServiceRole: 316 | Description: CodeBuild IAM Service Role 317 | Value: !GetAtt CodeBuildServiceRole.Arn 318 | 319 | CodePipelineServiceRole: 320 | Description: CodePipeline IAM Service Role 321 | Value: !GetAtt PipelineExecutionRole.Arn 322 | 323 | GitRepository: 324 | Description: Git repository HTTP URL 325 | Value: !GetAtt CodeRepository.CloneUrlHttp 326 | 327 | -------------------------------------------------------------------------------- /images/ami-builder-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/ami-builder-diagram.png -------------------------------------------------------------------------------- /images/ami-builder-initial-pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/ami-builder-initial-pipeline.png -------------------------------------------------------------------------------- /images/ami-builder-pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/ami-builder-pipeline.png -------------------------------------------------------------------------------- /images/build_phases.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/build_phases.png -------------------------------------------------------------------------------- /images/create_policy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/create_policy.png -------------------------------------------------------------------------------- /images/create_project.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/create_project.png -------------------------------------------------------------------------------- /images/deploy-to-aws.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/deploy-to-aws.png -------------------------------------------------------------------------------- /images/new_build.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/ami-builder-packer/c1bb2eda74a65fd6acc6a523d6dccaf669afba74/images/new_build.png -------------------------------------------------------------------------------- /packer_cis.json: -------------------------------------------------------------------------------- 1 | { 2 | "variables": { 3 | "vpc": "{{env `BUILD_VPC_ID`}}", 4 | "subnet": "{{env `BUILD_SUBNET_ID`}}", 5 | "aws_region": "{{env `AWS_REGION`}}", 6 | "ami_name": "Prod-CIS-Latest-AMZN-{{isotime \"02-Jan-06 03_04_05\"}}" 7 | }, 8 | "builders": [{ 9 | "name": "AWS AMI Builder - CIS", 10 | "type": "amazon-ebs", 11 | "region": "{{user `aws_region`}}", 12 | "source_ami_filter": { 13 | "filters": { 14 | "virtualization-type": "hvm", 15 | "name": "amzn-ami-hvm-2017.09.*-gp2", 16 | "root-device-type": "ebs" 17 | }, 18 | "owners": ["137112412989", "591542846629", "801119661308", 19 | "102837901569", "013907871322", "206029621532", 20 | "286198878708", "443319210888" 21 | ], 22 | "most_recent": true 23 | }, 24 | "instance_type": "t2.micro", 25 | "ssh_username": "ec2-user", 26 | "ami_name": "{{user `ami_name` | clean_ami_name}}", 27 | "tags": { 28 | "Name": "{{user `ami_name`}}" 29 | }, 30 | "run_tags": { 31 | "Name": "{{user `ami_name`}}" 32 | }, 33 | "run_volume_tags": { 34 | "Name": "{{user `ami_name`}}" 35 | }, 36 | "snapshot_tags": { 37 | "Name": "{{user `ami_name`}}" 38 | }, 39 | "ami_description": "Amazon Linux CIS with Cloudwatch Logs agent", 40 | "associate_public_ip_address": "true", 41 | "vpc_id": "{{user `vpc`}}", 42 | "subnet_id": "{{user `subnet`}}" 43 | }], 44 | "provisioners": [{ 45 | "type": "shell", 46 | "inline": [ 47 | "sudo pip install ansible==2.7.9" 48 | ] 49 | }, 50 | { 51 | "type": "ansible-local", 52 | "playbook_file": "ansible/playbook.yaml", 53 | "role_paths": [ 54 | "ansible/roles/common" 55 | ], 56 | "playbook_dir": "ansible", 57 | "galaxy_file": "ansible/requirements.yaml" 58 | }, 59 | { 60 | "type": "shell", 61 | "inline": [ 62 | "rm .ssh/authorized_keys ; sudo rm /root/.ssh/authorized_keys" 63 | ] 64 | } 65 | ] 66 | } 67 | --------------------------------------------------------------------------------