From Commit to Two Regions: A Multi-Region CI/CD Pipeline with AWS CodePipeline and CodeDeploy
Build a CI/CD pipeline on AWS DevOps tools: GitHub triggers CodePipeline, CodeDeploy ships to EC2 in two Regions, with a manual approval gate and an automated Lambda readiness check.
- Author
- Navinda Chandrasiri
- Published
- Reading time
- 14 min read

On this page
- What we are building
- The starting point
- Step 1: Understand the application bundle
- Step 2: Configure CodeDeploy for both Regions
- The service role
- The application and deployment groups
- Step 3: Create the first pipeline (Source and Deploy)
- Step 4: Add the approval gate and the second Region
- Step 5: Prove it end to end from CloudShell
- Step 6: Replace the human check with a Lambda function
- Controlling the pipeline
- Troubleshooting
- Clean up
- Where to take it next
- Wrapping up
Pushing code is the easy part. The hard part is getting that code onto the right servers, in the right order, in more than one place, with a human (or a script) able to say "stop, not yet" before it reaches production.
In this walkthrough we build exactly that with AWS's own DevOps services. A push to GitHub starts a pipeline. The pipeline deploys a simple web page to EC2 instances in us-west-2 (Oregon) automatically, then waits at an approval gate, and only then deploys to us-east-1 (N. Virginia). At the end we replace the human check with a Lambda function that verifies the deployment on its own.
The application is deliberately tiny, a single web page, so the focus stays on the pipeline rather than the app.
What we are building#
By the end you will have:
- A release pipeline that starts on every push to your repository.
- Automatic deployment to a first Region.
- A manual approval gate before the second Region.
- An optional automated readiness check written as a Lambda function.
Here are the services involved and the job each one does:
| Service | Role in this pipeline |
|---|---|
| Amazon EC2 | The compute that runs the web page, using Amazon Linux |
| AWS CloudFormation | Created the infrastructure and supporting resources before we start |
| GitHub | The code repository and the pipeline's trigger |
| AWS CodeDeploy | Installs the application onto the EC2 instances in each Region |
| AWS CodePipeline | Orchestrates the stages and starts automatically when the source changes |
| AWS Lambda | Runs the automated check of the deployed page |
| AWS CloudShell | A browser-based shell where we edit the code and push, to prove the pipeline reacts |
The starting point#
Before touching the pipeline, three things already exist. This is worth stating clearly, because most "my pipeline does not work" problems trace back to one of them being missing.
- The infrastructure. CloudFormation provisioned two EC2 environments: two instances in us-west-2 (Region 1) and three instances in us-east-1 (Region 2). Every instance runs the CodeDeploy agent, a small program that polls CodeDeploy for work, and has an IAM role that lets it do so.
- The application bundle. Next to the web page in the repository sit an
appspec.ymlfile and a few helper scripts. The AppSpec file tells CodeDeploy what to copy and which scripts to run. - A Lambda function. When invoked, it checks some text on a web page. We will wire it in during the last step.
Figure 1: The environment CloudFormation created. Two Regions, five EC2 instances, each running the CodeDeploy agent.
A CloudFormation template describes the whole thing, so the environment can be built, rebuilt and deleted in minutes. That is infrastructure as code doing what it does best: the stage is set the same way every time, and the pipeline only has to worry about the application.
Step 1: Understand the application bundle#
CodeDeploy does not guess how to install your app. It reads appspec.yml from the root of your bundle. A typical file for a static web page on Amazon Linux looks like this (your repository's copy will differ in the details):
version: 0.0
os: linux
files:
- source: /index.html
destination: /var/www/html/
hooks:
BeforeInstall:
- location: scripts/install_dependencies.sh
timeout: 300
runas: root
ApplicationStart:
- location: scripts/start_server.sh
timeout: 300
runas: root
ApplicationStop:
- location: scripts/stop_server.sh
timeout: 300
runas: rootThe files section says what to copy and where. The hooks section attaches scripts to points in the deployment lifecycle. On each instance CodeDeploy runs them in this order: ApplicationStop, DownloadBundle, BeforeInstall, Install, AfterInstall, ApplicationStart and ValidateService.
And the scripts are short:
#!/bin/bash
# scripts/install_dependencies.sh
dnf install -y httpd#!/bin/bash
# scripts/start_server.sh
systemctl enable httpd
systemctl start httpd#!/bin/bash
# scripts/stop_server.sh
# On the very first deployment there is nothing to stop, so never fail here.
systemctl stop httpd || trueTwo details save a lot of debugging time. The paths in appspec.yml are relative to the root of the bundle, and a script saved with Windows (CRLF) line endings will fail with a confusing "file not found" style error. Keep the scripts in LF format.
Step 2: Configure CodeDeploy for both Regions#
CodeDeploy is the continuous deployment half of the story: it installs the application on your infrastructure. It needs to know two things, what to deploy (an application) and where to deploy it (a deployment group).
Here is the part that surprises people: CodeDeploy resources are regional. An application created in us-west-2 does not exist in us-east-1. You configure it once per Region.
The service role#
CodeDeploy itself needs permission to look at your instances. Create an IAM role that CodeDeploy can assume (trusted entity: the CodeDeploy service) and attach the AWS managed policy AWSCodeDeployRole. IAM is global, so one role serves both Regions.
The application and deployment groups#
In the console, open CodeDeploy, create an application with the EC2/On-premises compute platform, then create a deployment group. The same thing from the CLI, for Region 1:
aws deploy create-application \
--application-name WebApp \
--compute-platform Server \
--region us-west-2
aws deploy create-deployment-group \
--application-name WebApp \
--deployment-group-name WebApp-Region1 \
--service-role-arn arn:aws:iam::123456789012:role/CodeDeployServiceRole \
--ec2-tag-filters Key=Name,Value=WebApp-Region1,Type=KEY_AND_VALUE \
--deployment-config-name CodeDeployDefault.OneAtATime \
--region us-west-2Repeat it for Region 2 with --region us-east-1 and the matching tag. The settings that matter:
- Environment configuration. CodeDeploy finds its targets by EC2 tag. If the tag filter matches nothing, the deployment has no instances to work on, which is the number one first-time mistake.
- Deployment configuration.
OneAtATimeupdates one instance, then the next.AllAtOnceis faster but takes every instance through the change together. - Load balancer. Not used here. We will come back to that at the end.
Step 3: Create the first pipeline (Source and Deploy)#
CodePipeline is the orchestrator. It does not install anything itself. It watches the repository, takes a snapshot of the code, hands it to CodeDeploy, and tracks the result.
Create a pipeline in the console and configure two stages. I created the pipeline in us-west-2, next to Region 1.
| Stage | Action | Provider | Region |
|---|---|---|---|
| Source | Source | GitHub (via GitHub App) | us-west-2 |
| Deploy | Deploy | AWS CodeDeploy (WebApp-Region1) | us-west-2 |
Some notes on each:
- Source. You authorise AWS to read your repository through a connection (AWS CodeConnections, formerly CodeStar Connections). Pick the repository and branch. A new push to that branch then starts the pipeline automatically, with no polling and no manual button.
- Build. We skip the build stage. A static page has nothing to compile. For a real application this is where tests and bundling would go.
- Deploy. Choose CodeDeploy, the application, and the Region 1 deployment group.
- Artifact store. CodePipeline keeps each revision as an artifact in an S3 bucket. The console creates and manages the bucket for you.
The pipeline runs as soon as it is created. Watch the two stages turn green, then take the public DNS name of one of the Region 1 instances and open it in a browser. The page should load.
Step 4: Add the approval gate and the second Region#
Now the interesting bit. We want Region 1 to receive every change automatically, but Region 2 only after somebody confirms that all is well.
Figure 2: The extended pipeline. Region 1 deploys automatically; Region 2 waits behind an approval gate.
Edit the pipeline and add two stages after the first Deploy stage:
- Approval with a Manual approval action. You can attach an Amazon SNS topic so reviewers get an email, add review instructions, and include a link to the Region 1 page so the reviewer knows what to check.
- Deploy-Region2 with a CodeDeploy action that targets the us-east-1 application and deployment group.
Two things deserve care:
- The second deploy is a cross-Region action. The pipeline lives in one Region, but this action runs in another. CodePipeline needs an artifact bucket in each Region it acts in, so that CodeDeploy in us-east-1 can read the bundle locally. The console creates the extra bucket for you. If you build the pipeline with code or the CLI, you must define one artifact store per Region yourself.
- Approvers need permissions too. Whoever clicks Approve must be allowed to call
codepipeline:PutApprovalResulton this pipeline, along with permission to read its state.
When a change flows through, the approval stage shows Waiting for approval. The reviewer opens the Region 1 page, checks it, and chooses Approve (or Reject, with a comment). Only then does the pipeline continue to Region 2.
Step 5: Prove it end to end from CloudShell#
A pipeline you have not triggered is a pipeline you cannot trust. Open AWS CloudShell, clone your repository, change the page and push:
git clone https://github.com/YOUR-USER/YOUR-REPO.git
cd YOUR-REPO
# make a visible change to the page
sed -i 's/Version 1/Version 2/' index.html
git add index.html
git commit -m "Update page to version 2"
git push origin mainAuthenticate the push with a personal access token or an SSH key. Use a token that is limited to this one repository and delete it when you are finished.
Then watch CodePipeline:
- Source picks up the new commit within moments.
- Deploy to Region 1 runs, and the Oregon instances serve "Version 2".
- The pipeline stops at Approval. The Region 2 instances still serve "Version 1", which is exactly what you want from a gate.
- After you approve, Deploy to Region 2 updates the three Virginia instances.
That pause between steps 2 and 4 is the whole point. A bad change has to get past Region 1 and a person before it can reach anything else.
Step 6: Replace the human check with a Lambda function#
Manual approval is great for a first version. It is also slow, easy to forget, and a person staring at a web page is not a very rigorous test. We can automate the "is Region 1 healthy?" question.
Figure 3: A Lambda function performs the region-readiness check, so the gate no longer depends on a person.
The function fetches the page from a Region 1 instance and looks for the text you expect. The detail that trips most people up is that a CodePipeline Lambda action must report its own result. CodePipeline invokes the function and then waits. If the function never calls PutJobSuccessResult or PutJobFailureResult, the action just hangs until it times out, even if your check passed.
import json
import urllib.request
import boto3
codepipeline = boto3.client("codepipeline")
def lambda_handler(event, context):
job = event["CodePipeline.job"]
job_id = job["id"]
# Configured on the pipeline action as the "User parameters" JSON string, e.g.
# {"url": "http://ec2-...compute.amazonaws.com", "expected_text": "Version 2"}
params = json.loads(
job["data"]["actionConfiguration"]["configuration"]["UserParameters"]
)
try:
with urllib.request.urlopen(params["url"], timeout=10) as response:
body = response.read().decode("utf-8")
if params["expected_text"] in body:
codepipeline.put_job_success_result(jobId=job_id)
else:
codepipeline.put_job_failure_result(
jobId=job_id,
failureDetails={
"type": "JobFailed",
"message": "Expected text was not found on the page",
},
)
except Exception as error:
codepipeline.put_job_failure_result(
jobId=job_id,
failureDetails={"type": "JobFailed", "message": f"Check failed: {error}"},
)The function's execution role needs permission to report the result, in addition to the basic logging permissions that Lambda uses:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"codepipeline:PutJobSuccessResult",
"codepipeline:PutJobFailureResult"
],
"Resource": "*"
}
]
}Then add an Invoke action from AWS Lambda to the Approval stage. Select the function and set its user parameters to the Region 1 URL and the text to look for. You can keep the manual approval right after it for belt and braces, or drop it once you trust the check. The pipeline's service role needs lambda:InvokeFunction for the function, and the console normally adds that when you pick it.
The result is a pipeline where a failed check stops the release before Region 2 is touched, with no human in the loop and a clear reason in the pipeline history.
Controlling the pipeline#
"Create and control" is the point of this exercise, so here are the levers you now have:
- Approve or reject a release at the gate, with a comment that is stored in the history.
- Disable the transition between two stages to freeze a promotion while you investigate:
aws codepipeline disable-stage-transition \
--pipeline-name WebAppPipeline \
--stage-name Deploy-Region2 \
--transition-type Inbound \
--reason "Holding while we investigate a Region 1 alert"- Re-run a failed stage after you fix the cause, without re-running everything before it.
- Start a release by hand with
aws codepipeline start-pipeline-execution --name WebAppPipeline. - Inspect state from a script with
aws codepipeline get-pipeline-state --name WebAppPipeline.
For a bad release that already shipped, deploy the previous good revision again through CodeDeploy, or push a revert commit and let the pipeline carry it through both Regions.
Troubleshooting#
| Symptom | Likely cause | What to check |
|---|---|---|
| Source stage fails or never starts | The GitHub connection is still pending, or lacks access to the repository | Complete the connection handshake and grant the app access to the repository |
| Deployment succeeds but nothing changed | The tag filter matched no instances | Compare the deployment group's tag filter with the real EC2 tags |
| Deployment stuck, then fails on the instance | The CodeDeploy agent is not running, or the instance role cannot read the artifact | Check the agent service on the instance and the instance profile permissions |
appspec.yml or script errors | Wrong paths, missing file, or CRLF line endings | Open the deployment's event log for the failing lifecycle hook |
| Region 2 deploy fails with artifact or bucket errors | No artifact store defined for that Region | Make sure the pipeline has an artifact bucket in us-east-1 |
| Lambda action hangs, then times out | The function never reported a job result | Confirm it calls the success or failure API, and that its role allows both |
| Lambda check fails with a network error | The instance's security group blocks HTTP | Allow inbound HTTP to the instances, and use the instance's public address |
Clean up#
These resources cost money while they exist, so delete them when you finish experimenting:
- Delete the pipeline, and the S3 artifact buckets it created in both Regions (empty them first).
- Delete the CodeDeploy applications in both Regions.
- Delete the CloudFormation stacks, which removes the EC2 instances and supporting resources.
- Delete the Lambda function and the personal access token you used from CloudShell.
Where to take it next#
This pipeline is a solid foundation, and it also shows where the next improvements would come from:
- Add a load balancer. Without one, each instance has its own address, so rolling deployments cannot keep a single endpoint available. An Application Load Balancer in each Region fixes that and unlocks blue/green deployments.
- Add a build and test stage. Run linting and unit tests before anything is deployed.
- Add a
ValidateServicehook. Let CodeDeploy fail a deployment on an instance that does not respond after install, and enable automatic rollback. - Describe the pipeline as code. CloudFormation built the environment, so let it define the pipeline too, and your whole release process becomes reviewable.
- Compare the alternatives. GitHub Actions can do the orchestration job too, and with OIDC it needs no stored AWS keys. Start with Goodbye Access Keys: Connecting GitHub Actions to AWS with OIDC, then see a full example in Zero Stored Secrets: Deploying Next.js to AWS with SST, OpenNext and GitHub OIDC.
Wrapping up#
The shape of the solution is simple, and it scales well beyond a web page. CodeDeploy knows how to install the application. CodePipeline knows when and in what order to do it. Lambda and approval gates decide whether to continue. Each service does one job, and you control the flow between them.
Push, deploy to the first Region, verify, then promote. Once that loop runs by itself, shipping stops being an event and becomes routine.
Related reading
From git push to Global CDN: Hosting a Secure Next.js Static Site on S3 and CloudFront with Terraform and CodePipeline
Learn to host a Next.js static export on a private S3 bucket with CloudFront, a custom domain, HTTPS, security headers, and automated GitHub to CodePipeline deployments using Terraform.
AWSTerraformCloudFrontS3
12 min readZero Servers, One Bucket: Deploying a Next.js Static Site to Amazon S3 with Terraform and CodePipeline
Host a Next.js static export on Amazon S3 website hosting and automate every deployment from GitHub using AWS CodePipeline, CodeBuild, and Terraform, with the trade-offs explained honestly.
AWSTerraformS3CodePipeline
12 min readThe GitHub Repository Playbook: Branching, Rulesets, Security, Releases and Recovery for a DevOps Project
A practical playbook for running a project on GitHub: branching, rulesets, security scanning, versioned releases, issue management, backups and disaster recovery, docs and standards.
GitHubDevOpsSecurityGit
24 min read