-
Notifications
You must be signed in to change notification settings - Fork 0
/
playbook.sh
executable file
·87 lines (74 loc) · 2.49 KB
/
playbook.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env bash
# This script is supposed to run a playbook.
# It doesn't matter where you call it from.
# `playbooks/` will automatically be prepended to the path, while `.yml` will be appended.
# This results in `$0 <ansible_args> <playbook_name_without_yml>
# Fail on errors and unset variables
set -e
set -o nounset
# Try to run in nix-shell
if hash nix-shell &>/dev/null; then
if [ -z "${IN_STUVUS_NIX_SHELL:-}" ]; then
args="${0}"
for param in "${@}"; do
args="${args} \"${param}\""
done
exec nix-shell --arg inPlaybook true --run "${args}"
fi
fi
if [ "${#}" -lt 1 ]; then
echo "Usage: ${0} <ansible_args> <playbook_name_without_yml>"
exit 1
fi
# Get the path of the playbook to execute
playbook="${!#}"
# Remove the last parameter
set -- "${@:1:$(($#-1))}"
# Prepare playbook execution
cd "$(dirname "$(readlink -f "${0}")")/.." || exit 255
# Check if playbook exists
if [ "${playbook}" != all ] && [ ! -f "${PWD}/playbooks/${playbook}.yml" ]; then
echo "${PWD}/${playbook} does not exist"
exit 1
fi
# Build environment
declare -a environment
parseEnvironmentFile() {
while IFS= read -r line; do
# Skip empty lines
[ -z "${line}" ] && continue
# Skip comments
[[ "${line}" =~ ^[[:space:]]*#.*$ ]] && continue
# See if we need to take the variable from the parent environment
if [ "$(echo "${line}" | cut -d'=' -f2-)" = '' ]; then
# This gets the name of the variable
name="$(echo "${line}" | cut -d '=' -f1 | xargs)"
# Ignore missing variables and assign
[ -z "${!name:-}" ] || environment+=("${name}=${!name:-}")
else
# Append to environment array
environment+=("${line}")
fi
done < "${1}"
}
# Try both the normal and local environment
parseEnvironmentFile environment
[ -f environment.local ] && parseEnvironmentFile environment.local
if [ "${playbook}" = all ]; then
scripts/mkplaybook.py
else
# Create a temporary playbook copy at the ansible root directory.
# This workaround is needed to allow template or macro includes from tasks
cp "playbooks/${playbook}.yml" ./.playbook.yml
fi
trap 'rm ./.playbook.yml' INT TERM EXIT
export "${environment[@]}"
for collection in ${ANSIBLE_GALAXY_COLLECTIONS:-}; do
echo "[playbook.sh] Installing ansible-galaxy dependency \"${collection}\" ..."
# Replace . by /
[ ! -e $HOME/.ansible/collections/ansible_collections/"${collection//\./\//}" ] \
&& ansible-galaxy collection install "$collection"
done
# Go!
echo "[playbook.sh] Running playbook ..."
exec "${ANSIBLE_PLAYBOOK:-ansible-playbook}" "${@}" "./.playbook.yml"