├── .gitignore ├── LICENSE ├── README.md ├── deployment-pipeline ├── artifact-buckets.yaml ├── buildspec.yaml ├── create-artifact-buckets.sh ├── create-pipeline.sh ├── pipeline.yaml └── update-pipeline.sh ├── dev-deploy.sh ├── images ├── cross-region-symbols.png └── example-output.png ├── multiregion-build.sh ├── package-lock.json ├── package.json ├── src └── lambda.js └── template.yaml /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /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 | # Multi Region CodePipeline example 2 | 3 | This is a "walking skeleton" application that you can modify to create a continuously deployed AWS application 4 | using AWS CodePipeline, to multiple AWS regions. If you don't know what "AWS Regions" or CodePipeline are, or why you might want them, then you might want to do some Googling before using this example. 5 | 6 | The following core AWS services are used in example. 7 | 8 | * The application is a simple [AWS Lambda](https://aws.amazon.com/lambda/) function (defined in `template.yaml`), that is deployed using [SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) / [CloudFormation](https://aws.amazon.com/cloudformation/). This is purely an example - the same technique can be used for significantly more complicated applications. 9 | * The deployment pipeline is implemented using [AWS CodePipeline](https://aws.amazon.com/codepipeline/) (defined in `deployment-pipeline/pipeline.yaml`) 10 | * The deployment pipeline makes use of [AWS CodeBuild](https://aws.amazon.com/codebuild/), defined within the pipeline template, plus also `deployment-pipeline/buildpec.yaml`, using the build script `multiregion-build.sh` 11 | 12 | In summary, by using this example you will have a continuously deployed application, targeting multiple AWS regions, using only AWS services, a single CodePipeline instance, and zero custom tasks or custom resources. 13 | 14 | The documentation with this example assumes you have a working knowledge of using the AWS CLI from a terminal, CloudFormation, and some modicum of familiarity of CodePipeline and CodeBuild. 15 | 16 | ![Example](images/example-output.png "Example of 2 region deployment") 17 | 18 | ## How to create the pipeline 19 | 20 | 1. Fork this repository to your own GitHub repository (or elsewhere.) 21 | 22 | 1. By default the application will use the Github repository `symphoniacloud/multi-region-codepipeline` as its source repository. Update the `GitHubOwner` and `GitHubRepo` default parameter values in `deployment-pipeline/pipeline.yaml` for your values. Alternatively if you're not using Github then change the Pipeline `Source` stage (but that's out of scope for this readme.) 23 | 24 | 1. Assuming you are using GitHub then create a new GitHub personal access token for this application. See [here](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) for how to do this - CodePipeline needs just the `repo` scope permissions. I recommend you name the token for this particular pipeline, at least to get started, and that you store the token somewhere safe, like a password manager. 25 | 26 | 1. By default the application CloudFormation stack will be named `multi-region-codepipeline-app`, and the CodePipeline stack will be named `multi-region-codepipeline`. If / when you want to change these then update the following files, looking for references to `multi-region-codepipeline` : 27 | * `deployment-pipeline/create-artifact-buckets.sh` 28 | * `deployment-pipeline/create-pipeline.sh` 29 | * `deployment-pipeline/update-pipeline.sh` 30 | * `deployment-pipeline/artifact-buckets.yaml` 31 | * `deployment-pipeline/pipeline.yaml` 32 | * `package.json` 33 | * `template.yaml` 34 | 35 | 1. By default the application will be deployed to us-east-1 (N Virginia) and us-west-2 (Oregon). If / when you want to change this list then update the following files, looking for references to these regions: 36 | * `deployment-pipeline/create-artifact-buckets.sh` 37 | * `deployment-pipeline/pipeline.yaml` 38 | * `deployment-pipeline/buildspec.yaml` 39 | * `multiregion-build.sh` 40 | 41 | 1. Commit all your changes to source control 42 | 43 | 1. Now from a terminal run the following (this assumes the AWS CLI is installed and configured). Make sure the terminal is configured to use the AWS region where you want the pipeline itself to run (or override using the `--region` flag), and that it is configured to use the account where the pipeline and application will run: 44 | 45 | ``` bash 46 | $ cd deployment-pipeline 47 | $ ./create-artifact-buckets.sh 48 | 49 | # Check new buckets have been created in correct regions in S3 console. Take the prefix, 50 | # everything up to `-region-name`, and use that as the second argument below 51 | 52 | $ ./create-pipeline.sh YOUR-GITHUB-TOKEN ARTIFACT-BUCKET-NAME-PREFIX 53 | ``` 54 | 55 | Once you've run this last command then watch both the CloudFormation and then CodePipeline consoles to evaluate whether the process has been successful. 56 | 57 | To test everything, after the pipeline has successfully completed it's first run, check that you have new lambda functions named `MyLambdaFunction-GENERATEDSTACKNAME` in each of your target regions. You can execute these Lambdas from the Web Console using any test event as input. 58 | 59 | ## How to update the pipeline 60 | 61 | When you need to update the application code or structure (as defined in `template.yaml`), or when you need to change how the application is built (either in the `multiregion-build.sh` or `deployment-pipeline/buildspec.yaml` files), then simply pushing your changes to source control will be sufficient - CodePipeline references these files from source on every pipeline run. 62 | 63 | If you need to change the structure of the CodePipeline itself then run `deployment-pipeline/update-pipeline.sh` with the same arguments that you ran `create-pipeline.sh`. 64 | 65 | If you need to add or change regions, then do the following: 66 | 67 | 1. Update the 4 files listed above in step 5 under creating the pipeline, changing the regions where referenced 68 | 2. If you are **adding** regions, then change `create-artifact-buckets.sh` to **just** specify the regions that you are adding 69 | 3. Re-run `create-artifact-buckets.sh`, and then update the pipeline as described above. 70 | 71 | ## How this works 72 | 73 | Back in the dim an distant past of 8 weeks ago (before November 12 2018), it was not possible to use CodePipeline for cross-region actions, and so if you wanted to do multi-region CD you either needed to create a CodePipeline for each region (bleurgh), create custom workflow (sigh), or not use CodePipeline (whaaah!) 74 | 75 | But as of November 2018 CodePipeline supports "[Cross-Region Actions](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-cross-region.html)", meaning none of the above work-arounds are necessary. Huzzah! If you look in `deployment-pipeline/pipeline.yaml` you'll see the new `Region:` property being used on the "Deploy" actions. We duplicate the deploy actions for each region, parallelizing them to speed up the total deployment process. 76 | 77 | ![Cross Region Actions](images/cross-region-symbols.png "Cross Region Actions") 78 | 79 | So Multi-region CD is now easy on AWS, right? Well, no, not quite, there are still some friction points. 80 | 81 | The main concern is that if you're deploying using CloudFormation / SAM, then you are still hamstrung by CloudFormation's limitation that the template and resources used during a CloudFormation deployment must be in a bucket in the same region that the CloudFormation stack is deployed to. In other words if you're deploying to `us-west-2` then the CloudFormation template, and artifacts it references, must also be in a bucket in `us-west-2`, and by extension you need a separate artifact bucket per region you're deploying to. 82 | 83 | The new cross-region CodePipeline support helps somewhat with this in that you can now provide a set of `ArtifactStores`, with one `ArtifactStore` per region. CodePipeline will automatically sync up the `ArtifactStores` during the course of the pipeline run. If you look in `deployment-pipeline/pipeline.yaml` you'll see the new `ArtifactStores:` property being used on the CodePipeline resource. 84 | 85 | However, we're still left with two problems: 86 | 87 | * How do we create the artifact store buckets in the first place? 88 | * How do we create packaged applications for each region? 89 | 90 | The first of these is a problem because you can't create S3 buckets in a CloudFormation template outside of the current region. For a single-region pipeline you can create an S3 bucket inline in the same template that the CodePipeline resources are defined in; with multi-region you can't. That means we need to create the buckets *before* creating the pipeline. 91 | 92 | For this reason this example app includes the `artifact-buckets.yaml` template, and the `create-artifact-buckets.sh` script, which needs to be run before creating the pipeline. 93 | 94 | It's possible that this might be fixable with a CloudFormation custom resource, but I haven't investigated that. 95 | 96 | The last problem is that we need separately packaged applications per region. I'm using SAM here, and specifically the `aws cloudformation package` command during the CodeBuild stage. We *could* run CodeBuild once per region, just like we're running CloudFormation once per region during the deployment stage, but that's a little wasteful for CodeBuild, especially for when our build times get longer. 97 | 98 | So instead, *during the build stage*, we run `aws cloudformation package` **once per region** , using the `--region` flag (see `multiregion-build.sh`, which is itself is referenced by the CodeBuild build spec `deployment-pipeline/buildspec.yaml`). This creates all of our artifacts, and now our application can happily be deployed. 99 | 100 | So, in summary, here's how this works: 101 | 102 | - Create pipeline S3 artifact buckets as prerequisites 103 | - Within the pipeline run CodeBuild in the primary region (the same region as CodePipeline itself), but produce artifacts during the Build stage for all regions, using the `--region` flag at `cloudformation package` time 104 | - Use the CodePipeline `ArtifactStores` construct, along with multiple parallel deployment actions each using the `Region:` property. 105 | 106 | ## Teardown 107 | 108 | :warning: Run these steps **in order**, otherwise you may end up with stranded resources: 109 | 110 | 1. Delete the application stacks **from all regions** 111 | 1. Delete all artifact buckets 112 | 1. Delete the pipeline stack 113 | 114 | ## Questions, Comments, Additions, Suggestions 115 | 116 | If you have any questions, comments, additions or suggestions please feel free to comment through GitHub, on twitter at [@mikebroberts](https://twitter.com/mikebroberts), or via email at mike@symphonia.io. 117 | 118 | If your company is looking for help using CodePipeline, CloudFormation, or architecture using AWS then please contact us at [Symphonia](https://www.symphonia.io/). 119 | 120 | ## TODO 121 | 122 | * Sort out IAM permissions in pipeline.yaml 123 | * Consider using CDK version (better for repetition of resources) 124 | * Consider custom resources, or something else, to allow cross-region buckets to be managed in `pipeline.yaml` file 125 | -------------------------------------------------------------------------------- /deployment-pipeline/artifact-buckets.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Description: Per-region prerequisites for multi region app 3 | 4 | Resources: 5 | # Used for CodePipeline and Cloudformation/SAM artifacts across stacks 6 | CodePipelineBuildArtifactBucket: 7 | Type: AWS::S3::Bucket 8 | Properties: 9 | # *** Change this when you want to change the name of the pipeline resources 10 | # Note that this is account aware, so you can safely deploy the same repo 11 | # to multiple accounts (bucket names are globally unique), but you don't have to do this. 12 | # With the way this setup works you MUST end the bucket name with -${AWS::Region}, so that 13 | # the buckets can be found by the pipeline template 14 | BucketName: !Sub 'multi-region-codepipeline-${AWS::AccountId}-${AWS::Region}' 15 | LifecycleConfiguration: 16 | Rules: 17 | - ExpirationInDays: 90 18 | Status: Enabled 19 | VersioningConfiguration: 20 | Status: Enabled 21 | -------------------------------------------------------------------------------- /deployment-pipeline/buildspec.yaml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | 3 | phases: 4 | install: 5 | commands: 6 | - pip install --upgrade awscli # https://github.com/awslabs/serverless-application-model/issues/93 7 | build: 8 | commands: 9 | - chmod u+x ./multiregion-build.sh 10 | - ./multiregion-build.sh 11 | 12 | artifacts: 13 | type: zip 14 | discard-paths: yes 15 | files: 16 | # *** Change this list to reflect the per-region files generated in multiregion-build.sh 17 | - target/packaged-template-us-east-1.yaml 18 | - target/packaged-template-us-west-2.yaml 19 | -------------------------------------------------------------------------------- /deployment-pipeline/create-artifact-buckets.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -eu 4 | 5 | # *** Change this region list to the regions you want to deploy your application to 6 | REGIONS="us-east-1 us-west-2" 7 | 8 | # *** Change this to the name of the stack that will be created *in each* region to manage 9 | # your codepipeline artifact bucket (calling it the same as your codepipeline stack, suffixed 10 | # with '-artifact-bucket' makes most sense) 11 | STACKNAME="multi-region-codepipeline-artifact-bucket" 12 | 13 | for REGION in $REGIONS 14 | do 15 | aws cloudformation create-stack --region $REGION --stack-name $STACKNAME --template-body file://artifact-buckets.yaml 16 | done 17 | -------------------------------------------------------------------------------- /deployment-pipeline/create-pipeline.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # *** Change this to the desired name of the Cloudformation stack of 4 | # your Pipeline (*not* the stack name of your app) 5 | CODEPIPELINE_STACK_NAME="multi-region-codepipeline" 6 | 7 | if [ -z ${1} ] 8 | then 9 | echo "PIPELINE CREATION FAILED!" 10 | echo "Pass your Github OAuth token as the first argument" 11 | exit 1 12 | fi 13 | 14 | if [ -z ${2} ] 15 | then 16 | echo "PIPELINE CREATION FAILED!" 17 | echo "Pass your Artifact Bucket Name Prefix as the second argument" 18 | exit 1 19 | fi 20 | 21 | set -eu 22 | 23 | aws cloudformation create-stack \ 24 | --capabilities CAPABILITY_IAM \ 25 | --stack-name $CODEPIPELINE_STACK_NAME \ 26 | --parameters ParameterKey=GitHubOAuthToken,ParameterValue=${1} ParameterKey=ArtifactBucketNamePrefix,ParameterValue=${2} \ 27 | --template-body file://pipeline.yaml 28 | -------------------------------------------------------------------------------- /deployment-pipeline/pipeline.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | # *** Change this to something useful for you! 3 | Description: Multi Region Codepipeline Example 4 | 5 | Parameters: 6 | # *** This value must always be passed in when creating / updating stack 7 | # "NoEcho" is set to true, for security, so token won't be visible when examining the resulting stack 8 | GitHubOAuthToken: 9 | Type: String 10 | NoEcho: true 11 | 12 | # *** This value must always be passed in when creating / updating stack 13 | # This value will be suffixed with `-${AWS::Region}` when locating buckets 14 | ArtifactBucketNamePrefix: 15 | Type: String 16 | AllowedPattern: "[A-Za-z0-9-]+" 17 | 18 | # *** The remaining parameters should either be: 19 | # - overridden via changing "Default" here (PREFERABLE, since then they're in source control) 20 | # - or you can pass them in when creating / updating the stack 21 | 22 | # *** The stack name for the actual application we're deploying 23 | ApplicationStackName: 24 | Type: String 25 | Default: multi-region-codepipeline-app 26 | AllowedPattern: "[A-Za-z0-9-]+" 27 | 28 | # *** The owner of the Github repo for this application. Or delete this if you're not using Github 29 | GitHubOwner: 30 | Type: String 31 | Default: symphoniacloud 32 | AllowedPattern: "[A-Za-z0-9-]+" 33 | 34 | # *** The Github repo for this application. Or delete this if you're not using Github 35 | GitHubRepo: 36 | Type: String 37 | Default: multi-region-codepipeline 38 | AllowedPattern: "[A-Za-z0-9-]+" 39 | 40 | # *** The Github branch for this particular pipeline. Or delete this if you're not using Github 41 | GitHubBranch: 42 | Type: String 43 | Default: master 44 | AllowedPattern: "[A-Za-z0-9-]+" 45 | 46 | Resources: 47 | GithubWebhook: 48 | Type: 'AWS::CodePipeline::Webhook' 49 | Properties: 50 | AuthenticationConfiguration: 51 | SecretToken: !Ref GitHubOAuthToken 52 | Filters: 53 | - JsonPath: "$.ref" 54 | MatchEquals: refs/heads/{Branch} 55 | Authentication: GITHUB_HMAC 56 | TargetPipeline: !Ref CodePipeline 57 | TargetAction: Source 58 | Name: MyGithubWebhook 59 | TargetPipelineVersion: !GetAtt CodePipeline.Version 60 | RegisterWithThirdParty: 'true' 61 | 62 | CodePipeline: 63 | Type: AWS::CodePipeline::Pipeline 64 | Properties: 65 | # *** Update this list to be the same as the region bucket parameters you created above 66 | ArtifactStores: 67 | - Region: us-east-1 68 | ArtifactStore: 69 | Type: S3 70 | Location: !Sub '${ArtifactBucketNamePrefix}-us-east-1' 71 | - Region: us-west-2 72 | ArtifactStore: 73 | Type: S3 74 | Location: !Sub '${ArtifactBucketNamePrefix}-us-west-2' 75 | RestartExecutionOnUpdate: true 76 | RoleArn: !GetAtt CodePipelineRole.Arn 77 | Stages: 78 | - Name: Source 79 | Actions: 80 | # Change this to a different Source type if you're not using GitHub 81 | - Name: Source 82 | InputArtifacts: [] 83 | ActionTypeId: 84 | Category: Source 85 | Owner: ThirdParty 86 | Version: 1 87 | Provider: GitHub 88 | OutputArtifacts: 89 | - Name: SourceCode 90 | Configuration: 91 | Owner: !Ref GitHubOwner 92 | Repo: !Ref GitHubRepo 93 | Branch: !Ref GitHubBranch 94 | PollForSourceChanges: false 95 | OAuthToken: !Ref GitHubOAuthToken 96 | RunOrder: 1 97 | - Name: Build 98 | Actions: 99 | - Name: Build 100 | ActionTypeId: 101 | Category: Build 102 | Owner: AWS 103 | Version: 1 104 | Provider: CodeBuild 105 | OutputArtifacts: 106 | - Name: BuildOutput 107 | InputArtifacts: 108 | - Name: SourceCode 109 | Configuration: 110 | ProjectName: !Ref CodeBuildProject 111 | RunOrder: 1 112 | - Name: Deploy 113 | Actions: 114 | # *** Duplicate / edit / delete these stacks as necessary for your desired regions *** 115 | # *** Change this name to match desired region 116 | - Name: DeployToUsEast1 117 | # *** Change this for desired region 118 | Region: us-east-1 119 | ActionTypeId: 120 | Category: Deploy 121 | Owner: AWS 122 | Provider: CloudFormation 123 | Version: '1' 124 | InputArtifacts: 125 | - Name: BuildOutput 126 | Configuration: 127 | ActionMode: CREATE_UPDATE 128 | Capabilities: CAPABILITY_IAM,CAPABILITY_AUTO_EXPAND 129 | RoleArn: !GetAtt CloudformationRole.Arn 130 | StackName: !Ref ApplicationStackName 131 | # *** Change this to match the region of this stack, 132 | # *** using the file generated in the build step 133 | TemplatePath: "BuildOutput::packaged-template-us-east-1.yaml" 134 | RunOrder: 1 135 | # *** Change this name to match desired region 136 | - Name: DeployToUsWest2 137 | # *** Change this for desired region 138 | Region: us-west-2 139 | ActionTypeId: 140 | Category: Deploy 141 | Owner: AWS 142 | Provider: CloudFormation 143 | Version: '1' 144 | InputArtifacts: 145 | - Name: BuildOutput 146 | Configuration: 147 | ActionMode: CREATE_UPDATE 148 | Capabilities: CAPABILITY_IAM,CAPABILITY_AUTO_EXPAND 149 | RoleArn: !GetAtt CloudformationRole.Arn 150 | StackName: !Ref ApplicationStackName 151 | # *** Change this to match the region of this stack, 152 | # *** using the file generated in the build step 153 | TemplatePath: "BuildOutput::packaged-template-us-west-2.yaml" 154 | RunOrder: 1 155 | 156 | CodeBuildProject: 157 | Type: AWS::CodeBuild::Project 158 | DependsOn: CodeBuildRole 159 | Properties: 160 | Artifacts: 161 | Type: CODEPIPELINE 162 | Environment: 163 | # Use a higher powered instance here if you need, see: 164 | # https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html 165 | ComputeType: BUILD_GENERAL1_SMALL 166 | # Use a different image for different types of source code, see: 167 | # https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html 168 | Image: aws/codebuild/nodejs:8.11.0 169 | # Use WINDOWS_CONTAINER here if using Windows 170 | Type: LINUX_CONTAINER 171 | # *** Update this list to be the same as the region bucket parameters you created above 172 | # Make sure that this is the same list expected in your build script 173 | EnvironmentVariables: 174 | - Name: US_EAST_1_ARTIFACT_BUCKET 175 | Value: !Sub '${ArtifactBucketNamePrefix}-us-east-1' 176 | - Name: US_WEST_2_ARTIFACT_BUCKET 177 | Value: !Sub '${ArtifactBucketNamePrefix}-us-west-2' 178 | ServiceRole: !Ref CodeBuildRole 179 | Source: 180 | Type: CODEPIPELINE 181 | BuildSpec: deployment-pipeline/buildspec.yaml 182 | 183 | CodeBuildRole: 184 | Type: AWS::IAM::Role 185 | Properties: 186 | AssumeRolePolicyDocument: 187 | Version: "2012-10-17" 188 | Statement: 189 | Effect: Allow 190 | Principal: 191 | Service: codebuild.amazonaws.com 192 | Action: sts:AssumeRole 193 | ManagedPolicyArns: 194 | - arn:aws:iam::aws:policy/AdministratorAccess #TODO: Reduce permissions 195 | 196 | CodePipelineRole: 197 | Type: AWS::IAM::Role 198 | Properties: 199 | AssumeRolePolicyDocument: 200 | Version: "2012-10-17" 201 | Statement: 202 | Effect: Allow 203 | Principal: 204 | Service: codepipeline.amazonaws.com 205 | Action: sts:AssumeRole 206 | ManagedPolicyArns: 207 | - arn:aws:iam::aws:policy/AdministratorAccess #TODO: Reduce permissions 208 | 209 | CloudformationRole: 210 | Type: AWS::IAM::Role 211 | Properties: 212 | AssumeRolePolicyDocument: 213 | Version: "2012-10-17" 214 | Statement: 215 | Effect: Allow 216 | Principal: 217 | Service: cloudformation.amazonaws.com 218 | Action: sts:AssumeRole 219 | ManagedPolicyArns: 220 | - arn:aws:iam::aws:policy/AdministratorAccess #TODO: Reduce permissions 221 | -------------------------------------------------------------------------------- /deployment-pipeline/update-pipeline.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # *** Change this to the desired name of the Cloudformation stack of 4 | # your Pipeline (*not* the stack name of your app) 5 | CODEPIPELINE_STACK_NAME="multi-region-codepipeline" 6 | 7 | if [ -z ${1} ] 8 | then 9 | echo "PIPELINE CREATION FAILED!" 10 | echo "Pass your Github OAuth token as the first argument" 11 | exit 1 12 | fi 13 | 14 | if [ -z ${2} ] 15 | then 16 | echo "PIPELINE CREATION FAILED!" 17 | echo "Pass your Artifact Bucket Name Prefix as the second argument" 18 | exit 1 19 | fi 20 | 21 | set -eu 22 | 23 | aws cloudformation update-stack \ 24 | --capabilities CAPABILITY_IAM \ 25 | --stack-name $CODEPIPELINE_STACK_NAME \ 26 | --parameters ParameterKey=GitHubOAuthToken,ParameterValue=${1} ParameterKey=ArtifactBucketNamePrefix,ParameterValue=${2} \ 27 | --template-body file://pipeline.yaml 28 | -------------------------------------------------------------------------------- /dev-deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -eu 4 | 5 | if [ -z ${1} ] 6 | then 7 | echo "Deploy FAILED!" 8 | echo "Pass the S3 bucket you would like to use for deployment artifacts as first argument" 9 | exit 1 10 | fi 11 | 12 | # Read the application name from the package.json file so that we don't need to duplicate it in this script 13 | STACK_NAME=$(cat package.json | tr -d '\n' | sed 's/.*"name": *"\([^"]*\)".*/\1/') 14 | SAM_BUCKET=${1} 15 | 16 | npm run clean 17 | # Delete node_modules, and run npm install --production, to avoid putting dev dependencies in lambda zip file 18 | rm -rf node_modules 19 | npm install --production 20 | npm run dist 21 | 22 | # Now perform deployment using AWS SAM package and deploy commands 23 | aws cloudformation package \ 24 | --template-file template.yaml \ 25 | --s3-bucket $SAM_BUCKET \ 26 | --output-template-file target/packaged-template.yaml 27 | 28 | aws cloudformation deploy \ 29 | --template-file target/packaged-template.yaml \ 30 | --stack-name $STACK_NAME \ 31 | --capabilities CAPABILITY_IAM 32 | 33 | # Deployment now complete, so read some values from AWS that we can display 34 | REGION=$(aws configure get region) 35 | WEB_CONSOLE_URL="https://console.aws.amazon.com/lambda/home?region=${REGION}#/applications/${STACK_NAME}" 36 | 37 | echo 38 | echo "** Serverless application deployed!" 39 | echo "** Application / Stack name: $STACK_NAME" 40 | echo 41 | echo "** AWS Console URL: ${WEB_CONSOLE_URL} **" 42 | echo -------------------------------------------------------------------------------- /images/cross-region-symbols.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/symphoniacloud/multi-region-codepipeline/268734df67c22154d6b8580ec64ef0d5f8addb5d/images/cross-region-symbols.png -------------------------------------------------------------------------------- /images/example-output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/symphoniacloud/multi-region-codepipeline/268734df67c22154d6b8580ec64ef0d5f8addb5d/images/example-output.png -------------------------------------------------------------------------------- /multiregion-build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # *** Change this for your desired regions. These environment variables are the 4 | # same as those defined in deployment-pipeline/pipeline.yaml 5 | if [ -z "$US_EAST_1_ARTIFACT_BUCKET" ] || 6 | [ -z "$US_WEST_2_ARTIFACT_BUCKET" ] 7 | then 8 | echo "Artifact bucket environment variables are not set correctly" 9 | exit 1 10 | fi 11 | 12 | sam_package () { 13 | echo "Packaging in region ${1} to bucket ${2}" 14 | aws cloudformation package \ 15 | --template-file template.yaml \ 16 | --s3-bucket ${2} \ 17 | --output-template-file target/packaged-template-${1}.yaml \ 18 | --region ${1} 19 | } 20 | 21 | npm run clean 22 | npm install --production 23 | npm run dist 24 | 25 | # *** Change this list of commands for the regions you require - change both the 1st and 2nd arguments! 26 | sam_package us-east-1 ${US_EAST_1_ARTIFACT_BUCKET} 27 | sam_package us-west-2 ${US_WEST_2_ARTIFACT_BUCKET} 28 | 29 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "multi-region-app", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "multi-region-app", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "clean": "rm -rf target packaged-template.yaml", 6 | "dist": "mkdir -p target; cp -R src package*.json target; cd target; npm install --production" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/lambda.js: -------------------------------------------------------------------------------- 1 | exports.handler = async (event, context) => { 2 | const message = `Lambda with ${context.memoryLimitInMB}MB memory invoked at ${new Date()}`; 3 | console.log("message"); 4 | console.log("Event was: "); 5 | console.log(JSON.stringify(event)) 6 | return message; 7 | }; -------------------------------------------------------------------------------- /template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | # ** Change this to something useful! 4 | Description: My Multi Region App 5 | 6 | Resources: 7 | MyLambdaFunction: 8 | Type: AWS::Serverless::Function 9 | Properties: 10 | CodeUri: ./target 11 | Handler: src/lambda.handler 12 | Timeout: 5 13 | Runtime: nodejs8.10 14 | 15 | --------------------------------------------------------------------------------