Cloud / IaC · Freelance

ECS Blue/Green Deployments with CodeDeploy and GitHub Actions

CloudFormation stack for ECS on EC2 where CodeDeploy performs blue/green deployments with auto-rollback, driven by GitHub Actions.

  • ECS
  • ALB
  • CodeDeploy
  • Lambda
  • CloudFormation
  • Secrets Manager
  • GitHub Actions
  • ECR

// Why this matters

An ECS blue/green deployment with CodeDeploy gives you the property that rolling updates do not: the new version runs fully, beside the old one, before any production traffic moves. If the new tasks fail health checks, nothing changed for users. If they pass and the application misbehaves later, rollback is a listener flip rather than a redeploy.

Teams running containers on EC2-backed ECS clusters often start with the default rolling update, which mixes versions during the rollout and has no clean abort. For services behind an API with strict compatibility needs, that is not good enough. Blue/green is the standard answer, and it is entirely configurable as code.

This is the setup I built for a freelance client: a CloudFormation stack for the cluster, load balancer and services, plus a GitHub Actions workflow that drives CodeDeploy. The pattern is independent of the application.

// The problem

ECS rolling updates replace tasks gradually. During the window both versions serve traffic, a failed version is only caught by the service circuit breaker, and getting back to the old version means another deployment. For a database-backed API that matters.

Blue/green on ECS requires several things to line up: a service with the CodeDeploy deployment controller, two target groups of the same type, a production listener, a CodeDeploy application and deployment group that reference all of them, and a deployment started with an AppSpec that names the new task definition. Each is simple, but missing one yields a service that looks fine and cannot be deployed.

At the time, CloudFormation had no native resource for an ECS deployment group, and secrets handling added another sharp edge: a template parameter holding a database URL is visible in the console and in stack events. Both needed a deliberate answer.

// The solution

Each service gets two target groups, a production listener on the ALB, and an optional test listener. The ECS service sets DeploymentController: CODE_DEPLOY and starts with the first target group. CodeDeploy then creates a replacement task set attached to the other group, waits for it to become healthy, shifts the listener, and terminates the old task set after a wait you control.

The deployment group was created through a Lambda-backed custom resource calling the CodeDeploy API. CloudFormation has since gained a native route using the AWS::CodeDeployBlueGreen transform, which replaces the service and drops the custom resource; if you are starting fresh, read that documentation first and fall back to the custom resource if the transform is too restrictive for your stack. The custom resource below also handles update and delete properly, which the quickest versions do not.

Delivery is a GitHub Actions workflow. Pull requests lint and test. Pushes to protected branches additionally build the image, push it to ECR tagged with the commit, register a new task definition revision from the current one with the image replaced, render an AppSpec, and call create-deployment. Branch decides environment: the environment type is part of every resource name, so staging and production cannot be confused. Authentication uses GitHub OIDC to assume a role, not long-lived keys.

Secrets are referenced by ARN in the task definition secrets block, so ECS injects them at start and the values never appear in template parameters. For a Fargate-based variant of the same pipeline see Auto-scaled Containerised API on ECS Fargate, and for the Kubernetes take on release safety see CloudFormation EKS Platform with Per-Service CI/CD.

How it flows flow1. Lint, test, build → 2. Image publish → 3. Revision file → 4. CodeDeploy → 5. ALB → 6. Rollback → 7. Data layer → 8. Secrets01Lint, test, build02Image publish03Revision file04 · GATECodeDeploy05ALB06Rollback07Data layer08Secrets
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Lint, test, buildGitHub Actions on push and pull request
  2. Image publishbuild and push to ECR
  3. Revision fileJSON referencing the new task definition
  4. CodeDeploy gateblue/green per service via a custom-resource deployment group
  5. ALBtwo target groups per service; listener rules switch traffic
  6. Rollbackautomatic on deployment failure
  7. Data layersnapshots on a schedule
  8. SecretsSecrets Manager references passed as parameters, not values
GitHub ActionsECRCodeDeployECSALBpush image tagged with commitregister new task definition revisioncreate-deployment with AppSpeccreate replacement task setregister tasks in idle target groupshift listener to new target groupterminate old task set (or roll back)
One blue/green deployment. CodeDeploy owns the traffic shift; the pipeline only starts it.
Pipeline stages flow1. Lint and test → 2. Build image → 3. Push → 4. Register task definition → 5. CodeDeploy → 6. Traffic shift → 7. Rollback01Lint and test02Build image03Push04Register taskdefinition05 · GATECodeDeploy06Traffic shift07Rollback
Pipeline stages. The gate is the CodeDeploy health and rollback logic.
  1. Lint and testpull request and push
  2. Build imagetag with commit SHA
  3. PushECR
  4. Register task definitionimage replaced, same secrets
  5. CodeDeploy gatereplacement task set, health checks
  6. Traffic shiftlistener to new target group
  7. Rollbackautomatic on failure

// Before you start

  • An AWS account with an existing VPC, public and private subnets, and an ECS cluster capacity provider or EC2 Auto Scaling group.
  • An ACM certificate for the HTTPS listener and an ECR repository per service.
  • AWS CLI v2, jq, and permission to create CodeDeploy applications, IAM roles and Lambda functions.
  • A GitHub repository with an IAM role trusted for its OIDC provider.
  • Secrets already stored in Secrets Manager (you pass only their ARNs).

// Step-by-step implementation

  1. 01 Network and parameters: keep secrets out of values

    Build the VPC in a separate template and import its outputs. The main template takes only references: subnet IDs, certificate ARN and the ARNs of secrets. A parameter that holds a secret value shows up in the console and in stack events; a parameter that holds an ARN does not leak anything.

    Put the environment type in every resource name. It makes the logs, alarms and IAM policies unambiguous, and it stops a production deployment group being matched by a staging pipeline.

  2. 02 Application Load Balancer with a pair of target groups

    Create the load balancer, one HTTPS listener and two target groups of target type instance (or ip for awsvpc mode). The listener initially forwards to the first group. CodeDeploy will rewrite the listener default action during deployment, so CloudFormation must not fight it: do not add a second listener rule that also points at these groups.

    Both groups need identical health checks. A mismatch means the replacement tasks pass on one group and fail on the other, which looks like a flaky deployment.

  3. 03 The task definition and an ECS service on the CodeDeploy controller

    The service declares DeploymentController: CODE_DEPLOY. That choice is immutable for a service, so decide before creating it. The container receives secrets through the Secrets list; the execution role is allowed secretsmanager:GetSecretValue on exactly those ARNs and nothing wider.

    The task definition in the template is only a starting point. From the first deployment on, the pipeline registers new revisions and CodeDeploy rolls them out, so CloudFormation should not manage subsequent revisions or it will revert them on the next stack update.

  4. 04 CodeDeploy application, role and the deployment-group custom resource

    The application uses the ECS compute platform. The service role is the AWS-managed role for ECS deployments. The deployment group is created by a custom resource, since a plain resource type did not exist. Handle Create, Update and Delete explicitly and always answer CloudFormation, or the stack hangs for an hour waiting for a response.

    Set automatic rollback on deployment failure, blue/green with traffic control, and a short termination wait for the old task set. Use an all-at-once traffic config for a simple cut-over, or a canary or linear config if you want gradual traffic shifting with alarms.

  5. 05 GitHub Actions: build, push and keep the pipeline keyless

    Use OIDC federation so the workflow assumes a role for the duration of the job; there are no stored access keys to leak or rotate. Gate deployment on branch: pull requests run lint and test only, protected branches continue to deploy. Tag images with the commit SHA so every deployment is traceable and a rollback target is obvious.

  6. 06 Register a new task definition and start the deployment

    The deploy step takes the family currently in use, swaps only the image, registers a new revision, renders an AppSpec pointing at it, and starts the deployment. Rendering with jq keeps the AppSpec generated, not hand-edited. The AppSpec must be passed as inline content for the CLI, so wrap it in the revision envelope.

    Then wait for the deployment. If CodeDeploy rolls back, the wait command exits non-zero and the workflow fails visibly.

  7. 07 Roll back on purpose and rehearse it

    Automatic rollback covers deployment failure. For bad behaviour that passes health checks, stop an in-flight deployment or redeploy the previous revision. Rehearse both in a test environment, because the first time should not be an incident.

// How to verify it works

  • aws ecs describe-services shows the service with deploymentController.type = CODE_DEPLOY and two task sets during a deployment.
  • During a deployment, aws elbv2 describe-target-health for the idle target group fills with healthy targets before the listener switches.
  • Break the health endpoint in a test build; the deployment ends in Failed and the listener still points at the original target group.
  • aws deploy get-deployment-group shows BLUE_GREEN, WITH_TRAFFIC_CONTROL and rollback on DEPLOYMENT_FAILURE.
  • The stack parameters and events in the console show only secret ARNs, never secret values.

// Design decisions and trade-offs

  • A custom-resource Lambda fills a CloudFormation gap.
  • Deploy only from protected branches; environment type is in every name.
  • Secrets referenced by ARN; network in a separate template.

// Pitfalls and lessons learned

  • The deployment controller type cannot be changed on an existing service. Choosing the wrong one means replacing the service.
  • A custom resource that does not answer CloudFormation hangs the stack. Always call the response helper in both the success and failure paths.
  • CloudFormation updates to the task definition revert what the pipeline registered. Let CodeDeploy own revisions after the first deploy.
  • Mismatched health checks between the two target groups cause deployments that pass on one side and fail on the other.
  • A very short deregistration delay speeds deployments up and drops in-flight requests. Match it to your longest request.
  • Long-lived access keys in repository secrets are a liability. Use OIDC and a role scoped to the deployment actions.

// Frequently asked questions

How do I do an ECS blue/green deployment with CodeDeploy?

Create an ECS service with the CODE_DEPLOY deployment controller, two ALB target groups and a listener, a CodeDeploy ECS application and deployment group, then start a deployment with an AppSpec that names the new task definition.

Does CloudFormation support ECS CodeDeploy deployment groups natively?

It does now, through the AWS::CodeDeployBlueGreen transform. The custom-resource approach shown here predates it and is still useful when the transform is too restrictive for your stack.

How does automatic rollback work?

The deployment group enables rollback on deployment failure. If the replacement tasks fail health checks or an alarm fires, CodeDeploy keeps or returns traffic to the original task set.

Can I do canary or linear traffic shifting?

Yes. Replace the all-at-once deployment configuration with a canary or linear ECS configuration and attach CloudWatch alarms to stop the shift automatically.

How should secrets reach the container?

Reference Secrets Manager ARNs in the task definition secrets block. ECS injects the values at start and the execution role is granted read on those ARNs only.

// The outcome

Blue/green releases with automatic rollback on failure.

// Where to take it next

  • Add a test listener and an AppSpec hook that runs smoke tests before traffic shifts.
  • Switch to canary traffic shifting with CloudWatch alarms for error rate and latency.
  • Move the cluster to Fargate and reuse the same deployment group design, as in Auto-scaled Containerised API on ECS Fargate.
  • Add image scanning and signature checks before the register step.

// Keep reading