Skip to content

Instantly share code, notes, and snippets.

@arikw
Last active October 23, 2019 20:54
Show Gist options
  • Save arikw/7d4229b25195abbe0cd13020469eb11c to your computer and use it in GitHub Desktop.
Save arikw/7d4229b25195abbe0cd13020469eb11c to your computer and use it in GitHub Desktop.
docker-machine command with default machine name
#!/bin/bash
set -euo pipefail
MACHINE_NAME=$(printf "%q" ${DOCKER_MACHINE_NAME:-null})
if [ "$MACHINE_NAME" == "null" ]; then
echo "Error: No docker machine env variables are set"
exit -1;
fi
DM_SPECIAL_COMMANDS=(
'config' 'env' 'inspect' 'ip' 'kill' 'provision'
'regenerate-certs' 'restart' 'scp' 'ssh' 'start'
'status' 'stop' 'upgrade'
)
PRINT_EXPLANATION=0
SCRIPT_NAME=`basename "$0"`
ARGS="$@"
FIRST_ARG="${1:-}"
SECOND_ARG="${2:-}"
LAST_ARG="${@: -1}"
if [ "$LAST_ARG" == "--explain" ]; then
# remove last arg
ARGS="${@:1:${#}-1}"
PRINT_EXPLANATION=1
fi
parse () {
if [ -z "$ARGS" ]; then
return
fi
# if using a docker-machine flag or an option, it's too complicated to parse
if [ ${FIRST_ARG:0:1} == '-' ]; then
# echo "skipped - option usage detected"
return
fi
USING_SPECIAL_COMMAND=0
for COMMAND in "${DM_SPECIAL_COMMANDS[@]}"; do
if [ "$COMMAND" == "$FIRST_ARG" ]; then
USING_SPECIAL_COMMAND=1
SPECIAL_COMMAND="$COMMAND"
break
fi
done
if [ $USING_SPECIAL_COMMAND == 0 ]; then
# echo "skipped - not using a special command"
return
fi
# Skip injection if machine name is already used in the original command
ALL_MACHINE_NAMES=$(docker-machine ls -t 0 --quiet)
GREP_ARGS=$(echo ${ALL_MACHINE_NAMES} | sed 's/ /\\|/g')
if [ ! -z "$(echo $ARGS | grep -w $GREP_ARGS)" ]; then
# echo "skipped - found a machine name in the command"
return
fi
ARGS=$(echo $ARGS | sed -e "s/^${SPECIAL_COMMAND}\b/${SPECIAL_COMMAND} $MACHINE_NAME/")
}
parse
if [ "$PRINT_EXPLANATION" == 1 ]; then
set -x
fi
docker-machine $ARGS
@arikw
Copy link
Author

arikw commented Oct 20, 2019

This bash script injects the default docker machine name into commands that are supported by the script.

The default machine name is taken from DOCKER_MACHINE_NAME env variable.
Usage example:

dm ssh

This will run docker-machine ssh $DOCKER_MACHINE_NAME

The supported commands are config, env, inspect, ip, kill, provision, regenerate-certs, restart, scp, ssh, start, status, stop and upgrade

The script will not inject the default machine name if a supported command is not used as the first arguments or if there's a use of an existing machine name in the command.
This means that running dm ssh dev, will run docker-machine ssh dev as usual without the usage of DOCKER_MACHINE_NAME env variable.

You can add --explain as last parameter to print the actual command that the script runs.

To use this script, download the dm file and make it executable by running chmod +x dm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment