Search code examples
amazon-web-servicesdockeramazon-ecsaws-codepipeline

Update ECS task definition image tag when new image tag


I want my ECS task definition image tag updated when a newer tag exists.

In CodePipeline after I push the image with new tag, I try to update service with the following command, but it doesn't get the new image automatically, still the old one.

    - docker push ${DOCKERHUB_USER}/aws-dummy-api:${IMAGE_TAG}
    - aws ecs update-service --cluster my-cluster --service dummy-api-service --force-new-deployment --region eu-central-1

So how to get the new image tag automatically when I push a new tag?


Solution

  • It seems I need to create a new revison with the new image tag, and update the ECS service.

    Following this github issue, I managed like this in my CodePipeline buildspec.yml:

    build:
        commands:
            - docker build -t $FULL_IMAGE --target prod .
            - docker push $FULL_IMAGE
    post_build:
        commands:
            - TASK_DEFINITION=$(aws ecs describe-task-definition --task-definition "$TASK_FAMILY" --region "$AWS_DEFAULT_REGION")
            - NEW_TASK_DEFINITION=$(echo $TASK_DEFINITION | jq --arg IMAGE "$FULL_IMAGE" '.taskDefinition | .containerDefinitions[0].image = $IMAGE | del(.taskDefinitionArn) | del(.revision) | del(.status) | del(.requiresAttributes) | del(.compatibilities) |  del(.registeredAt)  | del(.registeredBy)')
            - NEW_TASK_INFO=$(aws ecs register-task-definition --region "$AWS_DEFAULT_REGION" --cli-input-json "$NEW_TASK_DEFINITION")
            - NEW_REVISION=$(echo $NEW_TASK_INFO | jq '.taskDefinition.revision')
            - aws ecs update-service --cluster ${ECS_CLUSTER} --service ${SERVICE_NAME} --task-definition ${TASK_FAMILY}:${NEW_REVISION}