Skip to content

Instantly share code, notes, and snippets.

@starkers
Last active July 4, 2017 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starkers/1103af4c1b8304eb583ddf1e7687e9f5 to your computer and use it in GitHub Desktop.
Save starkers/1103af4c1b8304eb583ddf1e7687e9f5 to your computer and use it in GitHub Desktop.
docker-enter gcp
#!/usr/bin/env bash
if [ -e $(dirname "$0")/nsenter ]; then
# with boot2docker, nsenter is not in the PATH but it is in the same folder
NSENTER=$(dirname "$0")/nsenter
else
NSENTER=nsenter
fi
if [ -z "$1" ]; then
echo "Usage: `basename "$0"` CONTAINER [COMMAND [ARG]...]"
echo ""
echo "Enters the Docker CONTAINER and executes the specified COMMAND."
echo "If COMMAND is not specified, runs an interactive shell in CONTAINER."
exit
fi
PID=$(docker inspect --format "{{.State.Pid}}" "$1")
[ -z "$PID" ] && exit 1
shift
if [ "$(id -u)" -ne "0" ]; then
which sudo > /dev/null
if [ "$?" -eq "0" ]; then
LAZY_SUDO="sudo "
else
echo "Warning: Cannot find sudo; Invoking nsenter as the user $USER." >&2
fi
fi
# Prepare nsenter flags
OPTS="--target $PID --mount --uts --ipc --net --pid --"
# env is to clear all host environment variables and set then anew
if [ $# -lt 1 ]; then
# No arguments, default to `su` which executes the default login shell
$LAZY_SUDO "$NSENTER" $OPTS su -m root
else
# Has command
# "$@" is magic in bash, and needs to be in the invocation
$LAZY_SUDO "$NSENTER" $OPTS "$@"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment