Last active
July 10, 2020 19:41
-
-
Save davidalger/8f3517dc9fbb0dd9ff2eaeb238d3917c to your computer and use it in GitHub Desktop.
Shell script to wrap ansible runtime in a docker context using these images: https://github.com/davidalger/docker-images-ansible
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
#!/usr/bin/env bash | |
set -euo pipefail | |
trap 'error "$(printf "Command \`%s\` on line $LINENO failed with exit code $?" "$BASH_COMMAND")"' ERR | |
function error { | |
>&2 printf "\033[31mERROR\033[0m: $@\n" | |
} | |
function fatal { | |
error "$@" | |
exit -1 | |
} | |
## find directory where this script is located following symlinks if neccessary | |
readonly BASE_DIR="$( | |
cd "$( | |
dirname "$( | |
(readlink "${BASH_SOURCE[0]}" || echo "${BASH_SOURCE[0]}") \ | |
| sed -e "s#^../#$(dirname "$(dirname "${BASH_SOURCE[0]}")")/#" | |
)" | |
)" >/dev/null \ | |
&& pwd -P | |
)" | |
cd "${BASE_DIR}" | |
## verify docker is running | |
if ! docker system info >/dev/null 2>&1; then | |
fatal "Docker does not appear to be running. Please start Docker." | |
fi | |
## parse arguments and default to ansible-playbook if first arg does not match predefined list | |
if [[ "${1:-}" =~ ^(ansible|sh|bash)$ ]] \ | |
|| [[ "${1:-}" =~ ^ansible-(config|connection|console|doc|galaxy|inventory|playbook|pull|test|vault)$ ]] | |
then | |
ANSIBLE_CMD=("${1:-}") | |
ANSIBLE_CMD+=("${@:2}") | |
else | |
ANSIBLE_CMD=("ansible-playbook") | |
ANSIBLE_CMD+=("${@:-}") | |
fi | |
## docker run with interactive tty by default but allow override via env variable | |
INTERACTIVE="${INTERACTIVE:-"-it"}" | |
## when on macOS environments use the special ssh auth socket | |
if [[ $OSTYPE =~ ^darwin ]]; then | |
SSH_AUTH_SOCK=/run/host-services/ssh-auth.sock | |
fi | |
## configure the docker run command for execution | |
ANSIBLE_IMG=${ANSIBLE_IMG:-"docker.io/davidalger/ansible:2.9"} | |
DOCKER_EXEC=(docker run --rm ${INTERACTIVE:-} -v "${BASE_DIR}":/opt/ansible -w /opt/ansible | |
--env SSH_AUTH_SOCK=/tmp/ssh-auth.sock -v "${SSH_AUTH_SOCK:-/dev/null}":/tmp/ssh-auth.sock | |
--env ANSIBLE_REMOTE_USER="${ANSIBLE_REMOTE_USER:-"$(whoami)"}" "${ANSIBLE_IMG}" "${ANSIBLE_CMD[@]}" | |
) | |
## fork execution and exit | |
trap '' ERR | |
exec "${DOCKER_EXEC[@]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment