Subscribe

Deploying to ECS from GitHub Actions

Part 9 of the shorty series: deploy every main commit to ECS Fargate from GitHub Actions. Render the task definition from the live family, run the migration as a one-off task, update the service, catch circuit breaker rollbacks and roll back by hand to any image tag.

Deploying to ECS from GitHub Actions

The pieces are all there now. Every push to main builds sha-<commit> and pushes it to ECR (part 6). The ECS service runs behind an ALB, created by Terraform (part 7). Terraform itself runs from pull requests (part 8). What's missing is the step that actually puts a new image on the service.

In this blog we will write that deploy workflow. After the image is pushed, it renders a new task definition from the one running now, runs the database migration as a one-off task, updates the service, waits until the new tasks are healthy, and fails loudly if ECS rolled back. A manual trigger lets you roll back to any older tag. This is part 9 of the shorty series. Level is intermediate.

Versions: aws-actions/amazon-ecs-render-task-definition@v1 (v1.9.1), aws-actions/amazon-ecs-deploy-task-definition@v2 (v2.6.4), aws-actions/configure-aws-credentials@v6, Terraform 1.17.1 for the IAM role. I checked the workflow with actionlint, ran the shell parts locally, and read the source of both ECS actions, because a couple of their behaviours decide how this workflow has to look. It hasn't run against a real ECS service while writing this, so read it as the recipe.

💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/CI-CD/GitHub-Actions/deploying-to-ecs-from-github-actions. Clone it and run each step yourself.

Who owns what

Part 7 left the service with ignore_changes = [task_definition]. That's the deal between the two pipelines. Terraform owns the shape of the task: CPU, memory, roles, env vars, secrets, logs. The deploy workflow owns one field, the image. So the workflow never keeps its own copy of the task definition JSON in the repo. It reads the latest revision of the shorty family from ECS, swaps the image, registers that as a new revision and points the service at it.

If someone changes an env var in Terraform, Terraform registers a new revision with the old image. The next deploy starts from that revision, so the env var change goes out with the next image. Nothing gets lost and nothing gets rolled back by accident.

The deploy role

One more role in infra/bootstrap, with the same trust as Terraform's apply role: only jobs running in the production environment.

data "aws_iam_policy_document" "deploy" {
  statement {
    sid = "TaskDefinitions"
    actions = [
      "ecs:DescribeTaskDefinition",
      "ecs:RegisterTaskDefinition",
    ]
    resources = ["*"] # these two don't support resource-level permissions
  }

  # The render action copies the old revision's tags (app, managed_by) into the
  # new one, and tagging on create needs its own permission.
  statement {
    sid       = "TagOnRegister"
    actions   = ["ecs:TagResource"]
    resources = ["*"]
    condition {
      test     = "StringEquals"
      variable = "ecs:CreateAction"
      values   = ["RegisterTaskDefinition"]
    }
  }

  statement {
    sid       = "RunMigration"
    actions   = ["ecs:RunTask"]
    resources = ["${local.ecs_prefix}:task-definition/shorty:*"]
  }

  statement {
    sid       = "WatchTasks"
    actions   = ["ecs:DescribeTasks"]
    resources = ["${local.ecs_prefix}:task/shorty/*"]
  }

  statement {
    sid       = "UpdateService"
    actions   = ["ecs:DescribeServices", "ecs:UpdateService"]
    resources = ["${local.ecs_prefix}:service/shorty/shorty"]
  }

  statement {
    sid       = "CheckImageExists"
    actions   = ["ecr:DescribeImages"]
    resources = [aws_ecr_repository.shorty.arn]
  }

  statement {
    sid     = "PassTaskRoles"
    actions = ["iam:PassRole"]
    resources = [
      "${local.iam_prefix}:role/shorty-execution",
      "${local.iam_prefix}:role/shorty-task",
    ]
    condition {
      test     = "StringEquals"
      variable = "iam:PassedToService"
      values   = ["ecs-tasks.amazonaws.com"]
    }
  }
}

The ecs:TagResource statement is one I would have missed. When the render action fetches a task definition by family, it asks ECS for the tags too and writes them into the new task definition. I noticed it only by reading its index.js: there's a line taskDefContents.tags = describeTaskDefResponse.tags. Our task definition has tags from the provider's default_tags in part 7, so registering the new revision is a register with tags, and ECS checks ecs:TagResource for that separately. The condition limits it to tagging during RegisterTaskDefinition.

iam:PassRole is needed because registering a task definition and running a task both hand the execution and task roles to ECS. The PassedToService condition means this role can pass them to ECS and to nothing else.

Then four repo variables: AWS_DEPLOY_ROLE_ARN from the bootstrap output, AWS_ACCOUNT_ID (already there from part 6), and ECS_SUBNETS and ECS_TASK_SECURITY_GROUP from part 7's terraform output subnets and terraform output task_security_group. The last two are for the migration task.

The workflow

.github/workflows/deploy.yml:

name: deploy

on:
  # After the image workflow has pushed sha-<commit> for a push to main.
  workflow_run:
    workflows: [image]
    types: [completed]
    branches: [main]
  # By hand, to roll back or to ship a release tag.
  workflow_dispatch:
    inputs:
      tag:
        description: "Image tag to deploy (sha-1a2b3c4 or v1.4.0)"
        required: true
        type: string

permissions:
  contents: read

concurrency:
  group: deploy-production
  cancel-in-progress: false

env:
  AWS_REGION: ap-south-1
  CLUSTER: shorty
  SERVICE: shorty
  FAMILY: shorty
  CONTAINER: shorty
  REPOSITORY: shorty

jobs:
  deploy:
    if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    timeout-minutes: 30
    environment:
      name: production
      url: https://s.example.com
    permissions:
      contents: read
      id-token: write

    steps:
      - name: Pick the image tag
        id: tag
        env:
          INPUT_TAG: ${{ inputs.tag }}
          HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
        run: |
          tag="${INPUT_TAG:-sha-${HEAD_SHA::7}}"
          if ! [[ "$tag" =~ ^(sha-[0-9a-f]{7}|v[0-9]+\.[0-9]+\.[0-9]+)$ ]]; then
            echo "::error::not an image tag we deploy: $tag"
            exit 1
          fi
          echo "tag=$tag" >> "$GITHUB_OUTPUT"
          echo "Deploying \`$tag\`" >> "$GITHUB_STEP_SUMMARY"

      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          aws-region: ${{ env.AWS_REGION }}

      - name: Check the image exists
        id: image
        env:
          TAG: ${{ steps.tag.outputs.tag }}
          ACCOUNT_ID: ${{ vars.AWS_ACCOUNT_ID }}
        run: |
          digest=$(aws ecr describe-images --repository-name "$REPOSITORY" \
            --image-ids imageTag="$TAG" --query 'imageDetails[0].imageDigest' --output text)
          echo "digest $digest"
          echo "uri=${ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${REPOSITORY}:${TAG}" >> "$GITHUB_OUTPUT"

      - name: Render task definition
        id: render
        uses: aws-actions/amazon-ecs-render-task-definition@v1
        with:
          task-definition-family: ${{ env.FAMILY }}
          container-name: ${{ env.CONTAINER }}
          image: ${{ steps.image.outputs.uri }}

      - name: Migrate, then deploy
        id: deploy
        uses: aws-actions/amazon-ecs-deploy-task-definition@v2
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          cluster: ${{ env.CLUSTER }}
          service: ${{ env.SERVICE }}
          # 1. run "/shorty migrate up" with the NEW image and wait for exit 0
          run-task: true
          run-task-launch-type: FARGATE
          run-task-subnets: ${{ vars.ECS_SUBNETS }}
          run-task-security-groups: ${{ vars.ECS_TASK_SECURITY_GROUP }}
          run-task-assign-public-IP: ENABLED
          run-task-started-by: deploy-migrate
          run-task-container-overrides: '[{"name": "shorty", "command": ["/shorty", "migrate", "up"]}]'
          wait-for-task-stopped: true
          # 2. update the service and wait until it is stable (or rolled back)
          wait-for-service-stability: true
          wait-for-minutes: 15

      - name: Show the service
        if: ${{ !cancelled() }}
        run: |
          aws ecs describe-services --cluster "$CLUSTER" --services "$SERVICE" \
            --query 'services[0].deployments[].{status:status,rollout:rolloutState,taskDef:taskDefinition,running:runningCount,reason:rolloutStateReason}' \
            --output table

      - name: Smoke test
        run: |
          for i in 1 2 3 4 5; do
            if curl -fsS --max-time 5 https://s.example.com/readyz; then exit 0; fi
            sleep 5
          done
          exit 1

Now the reasons, step by step.

Why workflow_run

I could have added a deploy job to the image workflow with needs: build. I kept it separate for two reasons. The image workflow also runs on pull requests and tags, and I don't want deploy logic tangled with that. And with its own workflow_dispatch, the same workflow is also the rollback button.

workflow_run fires when another workflow finishes, whether it passed or not, so the if checks conclusion == 'success'. The branches: [main] filter skips image runs for pull requests and tag pushes. One gotcha: workflow_run only works when the workflow file is on the default branch. While you write it on a feature branch, nothing happens and there is no error. That one basically confuses everybody once.

The tag comes from head_sha, the commit the image workflow built. Part 6 tags images sha- plus the first 7 characters, so sha-${HEAD_SHA::7} gives the exact same tag.

Checking the tag

The manual trigger takes free text, and that text ends up in an image URI. The regex only allows sha- with 7 hex characters or a vX.Y.Z version. I tried the step's logic in bash on my Mac with a few inputs:

OK sha-1a2b3c4
OK v1.4.0
REJECT latest
REJECT main
REJECT sha-1a2b3c4; rm -rf /

main is rejected on purpose. It moves, so "deploy main" doesn't say which code you deployed. Note also that the input goes through env: and not straight into the script as ${{ inputs.tag }}. Putting user input directly in run: is the classic script injection hole in GitHub Actions, securing GitHub Actions workflows has the details.

Then aws ecr describe-images fails the job if the tag doesn't exist in ECR. Without this, a typo in a manual rollback would register a task definition with an image that can't be pulled, and you'd find out ten minutes later from the circuit breaker.

Rendering from the family

task-definition-family: shorty makes the render action call DescribeTaskDefinition for the latest active revision, strip the fields that RegisterTaskDefinition doesn't accept (revision, status, ARN and so on), set the image of the shorty container and write the result to a temp file. Older examples always uses task-definition: task-definition.json with a file in the repo. That gives you two sources of truth, the JSON in the repo and Terraform, and they will drift. Reading from ECS avoids that.

Each deploy registers a new revision. They pile up, and deregistering them doesn't delete them. That's quite normal, just don't be surprised by revision 400.

Migrate first

With run-task: true, the deploy action registers the new revision and then starts a one-off Fargate task from it, with the command overridden to /shorty migrate up. With wait-for-task-stopped: true it waits for that task to stop and then checks every container's exit code. Any non-zero exit fails the step, and the service is never touched. In the action's code the run-task part comes before the service update, so the order is guaranteed.

This is the same idea as running goose migrations as a one-off ECS task, just done by the action instead of a script. The migration runs from the new image, so the new migrations are in it, and it uses the same subnets and security group as the service so it can reach Postgres.

See, the catch is that while the service rolls, old tasks are still running against the new schema for a minute or two. And if the deploy rolls back, the schema stays migrated. So every migration has to work with the previous version of the code. That's expand and contract: add the new column now, stop using the old one in a later release, drop it in a release after that.

Waiting, and noticing a rollback

wait-for-service-stability: true waits until the service is stable: the new tasks running, healthy in the target group, old tasks drained. Part 7 turned on the deployment circuit breaker with rollback = true. If new tasks keep failing, ECS gives up on the deployment and goes back to the previous one.

Here's the trap I found reading the deploy action. After a rollback, the service is stable again, on the old version. A plain "wait until stable" passes, and the job goes green while production still runs the old image. The action's changelog has the fix in v2.6.2 (April 2026): "Detect deployment rollback after service stabilization". The code now remembers the ID of the deployment it started and, after the wait, looks it up again:

Deployment <id> not found after stabilization. The deployment was likely rolled back by the deployment circuit breaker.
Deployment <id> FAILED: <reason>

Either one fails the step. With @v2 you get the latest v2, so you have it, but if you pinned an older v2 tag or a commit SHA from before that, the job can lie to you. Worth checking.

wait-for-minutes: 15 is the upper limit. A normal shorty deploy is two new tasks, two health checks, 30 seconds of deregistration delay. A few minutes. If it takes 15, something is wrong anyway.

The "Show the service" step prints the deployments table even when the deploy fails, so the reason (rolloutStateReason) is right in the log without opening the console. The smoke test calls /readyz through the real domain and the ALB, which checks DNS, TLS, the listener and that Postgres answers.

Rolling back by hand

The circuit breaker handles "new tasks don't start". It doesn't handle "new tasks start fine but the code is wrong". For that:

gh workflow run deploy.yml -f tag=sha-1a2b3c4

or the "Run workflow" button on the Actions page. Same steps, an older tag. The migration step runs too. The older image has no migration the database hasn't seen, so goose should find nothing to do, but watch that step's log the first time you try it. Rolling back the image never rolls back the database, which is one more reason for expand and contract.

If you'd rather have ECS roll back on errors and not only on failed health checks, the service has an alarms block that rolls back when a CloudWatch alarm fires during a deploy, like an alarm on ALB 5xx. CloudWatch for developers shows how to make that alarm. Rolling deploys with rollback is one strategy out of several, deployment strategies compares the others.

Approval or not

The job uses the production environment, because the deploy role trusts only environment:production. In part 8 that environment got required reviewers for Terraform applies. So every merge to main now waits for someone to click approve before it deploys. That's continuous delivery. If you want every green commit to go out by itself (continuous deployment, see CI/CD explained), make a second environment without reviewers, say production-deploy, limited to the main branch, and change the deploy role's trust to repo:fenixara/shorty:environment:production-deploy. Terraform keeps its approval, image deploys don't wait.

I actually prefer the approval for now. shorty doesn't ship ten times a day, and one click is cheap.

concurrency: deploy-production with no cancelling means two quick merges deploy one after the other, in order. Cancelling a deploy in the middle would leave a half-finished rollout, the circuit breaker would sort it out, but I'd rather not need it.

The whole path

Push to main, then ci (lint, tests) and image (build, push sha-1a2b3c4) run. Image finishes, deploy starts, waits for approval, migrates, rolls the service, checks for a rollback and curls /readyz. Every step has its own role with only the permissions it needs, and no AWS key is stored anywhere.

That's the end of the main shorty path, from the design in part 0 to a deploy on ECS. If something here doesn't match what you see in your account, the Show the service table is the first place I'd look.