CI/CD — Force Redeploy AWS ECS Fargate For Same Docker Image NameTag With Terraform

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
resource "aws_ecs_service" "main" {
name = "my-app-service"
cluster = aws_ecs_cluster.main.id
task_definition = aws_ecs_task_definition.app.arn
desired_count = 2
launch_type = "FARGATE"
force_new_deployment = true

Why should it work?

aws ecs update-service — cluster c — service s — force-new-deployment

WorkAround

  • When using AWS ECR as docker repository:
data "aws_ecr_image" "app" {
repository_name = "my-image-name"
image_tag = "my-image-tag"
}
#this will pull the latest digest for the given image from ECR
resource "aws_ecs_task_definition" "app" {
family = "my-app-service-task"
execution_role_arn = "my-ecs-task-execution-role"
network_mode = "awsvpc"
requires_compatibilities = ["FARGATE"]
cpu = 512
memory = 1024
container_definitions = <<DEFINITION
[
{
"name": "my-app-name",
"image": "my-image-name:my-image-tag@${data.aws_ecr_image.app.image_digest}",
...
#this inclusion of data image_digest will enforce task definition to change and thus service will redeploy.
  • When not using AWS ECR as docker repository:
#terraform script:
resource "aws_ecs_task_definition" "app" {
family = "my-app-service-task"
execution_role_arn = "my-ecs-task-execution-role"
network_mode = "awsvpc"
requires_compatibilities = ["FARGATE"]
cpu = 512
memory = 1024
container_definitions = <<DEFINITION
[
{
"name": "my-app-name",
"image": "my-image-name:my-image-tag@${var.image_digest}",
...
#Running in pipeline or script:#Extract the digest ID of the image in a variable
image_digest=$(docker images my-image-name:my-image-tag --format '{{.Digest}}')
#Pass it to TF var
TF_VAR_image_digest=$image_digest terraform apply

Downside

Humble Request To Readers🙏

Donation😇

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Amith Kumar

Amith Kumar

Lead Full Stack & DevOps Engineer