How to detect changes in ECR image when using sam deploy and CloudFormation

Viewed 64

I have a CF template and ECR image referenced in this template

Image: !Sub <registry_id>.dkr.ecr.eu-central-1.amazonaws.com/<repo_name>:${AWS::StackName}

If I update an image and then run

sam deploy --template-file devops/templates/${CFFILENAME}.yml \
      --capabilities CAPABILITY_NAMED_IAM --stack-name "${STACK_NAME}" \
      --region ${AWS_DEFAULT_REGION} --no-fail-on-empty-changeset

It won't detect any changes and I have to run

aws ecs update-service --cluster Env-${STACK_NAME}-ClusterALB --service Env-Backend --force-new-deployment

To update ECS task later in the pipeline, but it is causing stack drift. I would like to avoid it and do it all in one step in my CI pipeline and only using CF. Is there any pretty way to do it?

1 Answers

After giving it a bit more thought - this is what I came up with. I introduced new parameter in my cloudformation file such as:

Parameters:
  ImageTag:
    Description: "Image SHA"
    Type: String

Then I referenced it in task definition

 ContainerDefinitions:
        - Name: admin
          Essential: true
          Image: !Sub <repo_id>.dkr.ecr.eu-central-1.amazonaws.com/<repo_name>:${AWS::StackName}-${ImageTag}

And passed in the parameter to SAM using --parameter-overrides as follows:

      sam deploy --template-file devops/templates/${CFFILENAME}.yml \
      --capabilities CAPABILITY_NAMED_IAM --stack-name "${STACK_NAME}" \
      --region ${AWS_DEFAULT_REGION} --no-fail-on-empty-changeset \
      --parameter-overrides ImageTag=${IMAGE_TAG}

And the image tag is generated during the pipeline in GitLab CI using commit SHA as follows:

  - IMAGE_TAG="$(echo $CI_COMMIT_SHA | head -c 8)"
Related