Skip to content

Instantly share code, notes, and snippets.

@allex
Last active November 19, 2024 08:37
Show Gist options
  • Save allex/42f93720be61ec33c0542855f5a0f543 to your computer and use it in GitHub Desktop.
Save allex/42f93720be61ec33c0542855f5a0f543 to your computer and use it in GitHub Desktop.
#!/bin/bash
# vim: set ft=sh fdm=manual ts=2 sw=2 sts=2 tw=85 et:
# ================================================
# Description: sync push local docker images to remote
# Last Modified: Tue Nov 19, 2024 16:36
# Author: Allex Wang ([email protected])
# GistID: 42f93720be61ec33c0542855f5a0f543
# GistURL: https://gist.github.com/42f93720be61ec33c0542855f5a0f543
# ================================================
set -euE
set -o pipefail
PROG=$(basename "$0")
host=
image_name=
image_file=
cmd=
pull=
platform=linux/amd64
die() {
echo >&2 "fatal: $1"
exit 1
}
show_help () {
cat << EOF
Usage: ${PROG} [options]
Options:
-h, --host Specify the host
--image-name Specify the image name
--image-file Specify the image file
--pull Pull the image
--platform Specify the platform if pull image
-c, --cmd Specify the command to execute after remote image been loaded
EOF
exit 0
}
if [ $# -eq 0 ]; then
show_help
fi
while test $# -gt 0; do
case "${1-}" in
-h | --host)
host="${2-}"
shift
;;
--image-name)
image_name="${2-}"
shift
;;
--image-file)
image_file="${2-}"
shift
;;
--pull)
pull=1
;;
--platform)
platform="${2-}"
shift
;;
-c | --cmd)
cmd="${2-}"
shift
;;
--help)
show_help
;;
*)
die "invalid paramater: $1"
;;
esac
shift
done
if [ -z "$host" ]; then
die "the host is mandatory and invalid"
fi
if [ "$pull" == "1" ]; then
echo "Pull image ${tag_name} (${platform}) ..."
docker pull "${tag_name}" --platform "${platform}"
fi
tmpdir="$(mktemp -d ".tmp.XXXXXXXXXX.d")/"
trap 'rm -rf -- "${tmpdir}"' 0 1 2 3 6 15
if [ ! -f "$image_file" ]; then
if [ -n "$image_name" ]; then
image_file=${tmpdir}$(echo "$image_name" | sed "s#/#_#g; s#:#-#g").tar
echo "bundle '$image_file' ..."
docker save "$image_name" > "$image_file"
echo "image been saved to => $image_file"
else
die "both image file and image name are empty"
fi
fi
echo "Push image to remote ..."
ssc ${PASSWD:+-P $PASSWD} -L --trace -c "$(cat <<-EOF
set -eux;
trap "rm -rf -- \"${tmpdir}\"" 0 1 2 3 6 15
docker load -i "${tmpdir}${image_file##*/}"
if [ -n "$cmd" ]; then eval ${cmd}; fi
EOF
)" "$image_file" "$host:${tmpdir}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment