51 lines
2.2 KiB
Bash
51 lines
2.2 KiB
Bash
#!/bin/bash
|
|
# Run Ansible from a container, so it never touches the laptop's own Ansible,
|
|
# Python or collections.
|
|
# source ansible-docker.sh
|
|
# ansible-docker build
|
|
# ansible-docker run # interactive shell
|
|
# ansible-docker run ansible-playbook playbooks/utils.yml -CD
|
|
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
|
|
echo "This script is meant to be sourced: source ansible-docker.sh"
|
|
exit 1
|
|
fi
|
|
|
|
_ansible_docker_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
_ansible_docker_image=homelab-ansible
|
|
|
|
function ansible-docker() {
|
|
local dir=$_ansible_docker_dir
|
|
case "$1" in
|
|
build)
|
|
docker build -t "$_ansible_docker_image" \
|
|
--build-arg UID="$(id -u)" --build-arg GID="$(id -g)" "$dir"
|
|
;;
|
|
run)
|
|
shift
|
|
if [[ -z "$SSH_AUTH_SOCK" || ! -S "$SSH_AUTH_SOCK" ]]; then
|
|
echo "No SSH agent (SSH_AUTH_SOCK). Start one and ssh-add your key first."
|
|
return 1
|
|
fi
|
|
if ! ip route get 10.0.0.1 2>/dev/null | grep -q wg; then
|
|
echo "Warning: 10.0.0.1 isn't routed through WireGuard. Is the tunnel up?"
|
|
fi
|
|
# vault/password must exist and be non-empty even unused: ansible.cfg points at it.
|
|
mkdir -p "$dir/vault" "$dir/kube"
|
|
[[ -s "$dir/vault/password" ]] || { echo "placeholder" > "$dir/vault/password"; chmod 600 "$dir/vault/password"; }
|
|
touch ~/.ssh/known_hosts
|
|
# --network host: reach 10.0.0.0/24 and 10.10.10.0/24 through the laptop's wg0.
|
|
# known_hosts is read-only and copied in, so the laptop's file is never
|
|
# written. Hosts first seen here are accepted again on each run.
|
|
docker run -it --rm --network host \
|
|
--mount type=bind,source="$dir",target=/home/ansible/ansible \
|
|
--mount type=bind,source="$SSH_AUTH_SOCK",target=/run/ssh-agent.sock \
|
|
--mount type=bind,source="$HOME/.ssh/known_hosts",target=/home/ansible/.ssh/known_hosts.laptop,readonly \
|
|
-e SSH_AUTH_SOCK=/run/ssh-agent.sock \
|
|
"$_ansible_docker_image" \
|
|
bash -c 'cp ~/.ssh/known_hosts.laptop ~/.ssh/known_hosts; exec "${@:-bash}"' _ "$@"
|
|
;;
|
|
*)
|
|
echo "Usage: ansible-docker build | run [command...]"
|
|
;;
|
|
esac
|
|
}
|