Skip to content
Latchkey

How to Deploy to Amazon ECS With Bitbucket Pipelines

Register a new task definition revision with the freshly pushed image, then aws ecs update-service --force-new-deployment and wait for the service to stabilize.

An ECS deploy points a service at a new task definition revision. Substitute the new image into the task definition JSON, register it, and update the service so ECS performs a rolling replacement.

Steps

  • Render the task definition JSON with the new image tag.
  • aws ecs register-task-definition to create a new revision.
  • aws ecs update-service --task-definition <arn> --force-new-deployment.
  • aws ecs wait services-stable so a failed deploy fails the pipeline.

Pipeline

bitbucket-pipelines.yml
image: amazon/aws-cli:2
pipelines:
  branches:
    main:
      - step:
          name: Deploy to ECS
          deployment: production
          script:
            - apk add --no-cache jq || yum install -y jq
            - >
              jq --arg IMG "$IMAGE_REPO:$BITBUCKET_COMMIT"
              '.containerDefinitions[0].image = $IMG' taskdef.json > taskdef.out.json
            - TASK_ARN=$(aws ecs register-task-definition --cli-input-json file://taskdef.out.json --query 'taskDefinition.taskDefinitionArn' --output text)
            - aws ecs update-service --cluster prod --service web --task-definition "$TASK_ARN" --force-new-deployment
            - aws ecs wait services-stable --cluster prod --services web

Gotchas

  • services-stable waits up to ~10 minutes; a stuck deploy will time out and fail the step.
  • Keep the task definition family name stable so revisions accumulate under it.
  • Prefer OIDC role assumption over static keys for the ECS calls.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →