Skip to content

Instantly share code, notes, and snippets.

@Mathieu-COSYNS
Last active April 10, 2024 12:40
Show Gist options
  • Save Mathieu-COSYNS/b644d2d5af07b27713d22b522e5e7a23 to your computer and use it in GitHub Desktop.
Save Mathieu-COSYNS/b644d2d5af07b27713d22b522e5e7a23 to your computer and use it in GitHub Desktop.
Build images from a docker compose file and tag them with current commit hash and tags
#!/bin/bash
# Docker registry to use to tag and push images
REGISTRY="" # If not set use Docker Hub
# Default compose file to use
COMPOSE_FILE="docker-compose.build.yml"
# Git info
GIT_COMMIT_HASH="$(git rev-parse HEAD)"
GIT_COMMIT_TAGS="$(git tag --points-at HEAD)"
# Command options defaults
HELP=false
PUSH=false
help() {
echo "Build images from a docker compose file and tag them with current commit hash and tags."
echo
echo "Usage: $0 [OPTIONS] [COMPOSE_FILE]"
echo
echo "Options:"
echo "-h, --help print this help message"
echo "--push push built images to the registry"
echo
}
build() {
echo "Building..."
docker compose -f "$COMPOSE_FILE" build \
--pull \
--build-arg GIT_COMMIT_HASH="$GIT_COMMIT_HASH" || exit 1
}
tag_and_push() {
IMAGES="$(docker compose -f "$COMPOSE_FILE" config --images)"
while IFS= read -r IMAGE || [[ -n $IMAGE ]]; do
while IFS= read -r TAG || [[ -n $TAG ]]; do
REMOTE_IMAGE="$IMAGE:$TAG"
if [ -n "$REGISTRY" ]; then
REMOTE_IMAGE="$REGISTRY/$REMOTE_IMAGE"
fi
echo "Tagging $IMAGE as $REMOTE_IMAGE"
docker image tag "$IMAGE" "$REMOTE_IMAGE" || (echo "Tagging failed" 1>&2 && exit 1)
if [ "$PUSH" = true ]; then
echo "Pushing $REMOTE_IMAGE"
docker image push "$REMOTE_IMAGE" || (echo "Push failed" 1>&2 && exit 1)
fi
done < <(printf '%s\n%s' "$GIT_COMMIT_HASH" "$GIT_COMMIT_TAGS")
done < <(printf '%s' "$IMAGES")
}
# Parse options
while getopts :h-: OPT; do # allow -h, and -- "with arg"
# support long options: https://stackoverflow.com/a/28466267/519360
if [ "$OPT" = "-" ]; then # long option: reformulate OPT and OPTARG
OPT="${OPTARG%%=*}" # extract long option name
OPTARG="${OPTARG#$OPT}" # extract long option argument (may be empty)
OPTARG="${OPTARG#=}" # if long option argument, remove assigning `=`
fi
case "$OPT" in
h | help) HELP=true ;;
push) PUSH=true ;;
*) help && exit 2 ;; # option
esac
done
shift $((OPTIND - 1)) # remove parsed options and args from $@ list
if [ -n "$1" ]; then
COMPOSE_FILE="$1"
fi
if [ "$HELP" = true ]; then
help
exit 0
fi
build
tag_and_push
services:
youservice:
image: project/youservice
build: ./sourcefolder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment