Skip to content

Instantly share code, notes, and snippets.

@iameli
Created September 2, 2016 02:04
Show Gist options
  • Save iameli/d99ab8b058ba6ca29ffdd803370facd1 to your computer and use it in GitHub Desktop.
Save iameli/d99ab8b058ba6ca29ffdd803370facd1 to your computer and use it in GitHub Desktop.
Script for translating container volume paths into their antecedent host paths.
#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
# We need to run a Docker container in Jenkins that mounts our current directory. Unfortunately,
# Jenkins is also in a container, so its current directory differs from the host directory. This
# script figures out the Docker ID of our current container and translates the path to a host path
# if necessary.
containerPath="$(cd "$1" && pwd)"
# We might be on a mac. See if this file even exists.
if [[ ! -f /proc/self/cgroup ]]; then
echo "$containerPath"
exit 0
fi
# Let's start by getting our Docker id. Adapted from
# http://stackoverflow.com/questions/20010199/determining-if-a-process-runs-inside-lxc-docker
dockerId="$(head -1 /proc/self/cgroup | awk -F/docker- '{print $2}' | sed 's/\.scope//')"
# If not a docker container, return $containerPath
if ! docker inspect "$dockerId" > /dev/null; then
echo "$containerPath"
exit 0
fi
# Get all the volume mounts of this container.
containerJson="$(docker inspect "$dockerId")"
sources=($(echo $containerJson | jq -r '.[].Mounts[].Source'))
destinations=($(echo $containerJson | jq -r '.[].Mounts[].Destination'))
# Translate the provided path, destination --> source.
for index in ${!sources[*]}; do
sourceDir="${sources[$index]}"
destDir="${destinations[$index]}"
containerPath="$(echo "$containerPath" | sed 's|'$destDir'|'$sourceDir'|')"
done
# Cool.
echo "$containerPath"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment