Skip to content

Instantly share code, notes, and snippets.

@wanieldilson
Created December 12, 2023 14:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wanieldilson/ecc773fc0551adf17fbaea6cb5ca0555 to your computer and use it in GitHub Desktop.
Save wanieldilson/ecc773fc0551adf17fbaea6cb5ca0555 to your computer and use it in GitHub Desktop.
Docker multi arch build and push

Conditional Docker Build and Push with terraform

How to use

Save your dockerfile in a folder called images, this terraform code will build and push a multi-archtecture image to ECR. Whenever you update the Dockerfile and associated image tag, the null resource will be triggered to "re-create" subsequently updating the image in ECR.

But I've made a change and want to keep the same tag

Then simply run terraform apply -replace=null_resource.build_and_push ,- don't forget to use the full resource address if this code is inside a module. E.g module.name.null_resource.build_and_push.

data "aws_ecr_authorization_token" "token" {
}
resource "aws_ecr_repository" "this" {
name = "image"
image_tag_mutability = "MUTABLE"
}
locals {
image_tag = "go-1.21.5" # Changing this tag will force a build and push on the next deploy
}
resource "terraform_data" "this" {
input = local.image_tag
}
resource "null_resource" "build_and_push" {
provisioner "local-exec" {
command = <<EOF
docker login ${data.aws_ecr_authorization_token.token.proxy_endpoint} -u AWS -p ${nonsensitive(data.aws_ecr_authorization_token.token.password)}
cd images
docker buildx create --name image
docker buildx build --builder image \
--platform linux/amd64,linux/arm64 \
--tag ${aws_ecr_repository.ukssbuilder.repository_url}:${local.image_tag} \
--push \
--file Dockerfile .
EOF
}
lifecycle {
replace_triggered_by = [terraform_data.image_tag]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment