Last active
February 2, 2020 21:49
-
-
Save tvon/edeaf08b5e68c651b89a7e5a7e4dbfd9 to your computer and use it in GitHub Desktop.
Add a label to a Docker image tarball.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Add a label to an image tarball (manifest v1). | |
# | |
# $ docker save alpine -o alpine.tar | |
# $ add-label alpine.tar org.mine.key foobar | |
# $ docker load -i alpine.tar | |
# $ docker inspect alpine | jq '.[].Config.Labels' | |
# { | |
# "org.mine.key": "foobar" | |
# } | |
set -euf -o pipefail | |
tarball=${1:-''} | |
key=${2:-''} | |
val=${3:-''} | |
if [[ -z "${tarball}" || -z "${key}" || -z "${val}" ]]; then | |
echo "Usage: add-label image.tar key value" && exit 1 | |
fi | |
workdir=$(mktemp -d) | |
imagedir=${workdir}/image | |
mkdir "${imagedir}" | |
cleanup() { | |
rc=${1:-0} | |
rm -rf "${workdir}" | |
exit "${rc}" | |
} | |
trap cleanup EXIT | |
tar -C "${imagedir}" -xf "${tarball}" | |
# Figure out which file is the config json. | |
config=$(jq -r '.[].Config' "${imagedir}/manifest.json") | |
# modify config.Labels to a tempfile | |
jq -c \ | |
--arg key "${key}" \ | |
--arg val "${val}" \ | |
'. * {config: { Labels: { ($key): $val }}}' "${imagedir}/${config}" \ | |
>"${workdir}/config.json" | |
# modify container_config.Labels and overwrite original file. | |
jq -c \ | |
--arg key "${key}" \ | |
--arg val "${val}" \ | |
'. * {container_config: { Labels: { ($key): $val }}}' "${workdir}/config.json" \ | |
>"${imagedir}/${config}" | |
mv -f "${tarball}" "${tarball}.orig" | |
pushd "${imagedir}" >/dev/null | |
# shellcheck disable=SC2046 | |
tar -cf "${workdir}/out.tar" $(ls) | |
popd >/dev/null | |
mv "${workdir}/out.tar" "${tarball}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment