.dotfiles/.bin/ansible-vault-manager
2024-12-09 21:22:29 +01:00

72 lines
1.5 KiB
Bash
Executable file

#!/usr/bin/env bash
project_dir="$(git rev-parse --show-toplevel)"
action="${1:-show}"
target="${2:-}"
if [ "$action" = "save" ]; then
target="" # Save all files
fi
if [ -z "$project_dir" ]; then
exit 1
fi
cd "$project_dir" || exit 1
url="$(git remote get-url origin)"
re="^(https|git)(:\/\/|@)([^\/:]+)[\/:]([^\/:]+)\/(.+)(.git)*$"
if [[ $url =~ $re ]]; then
#protocol=${BASH_REMATCH[1]}
#separator=${BASH_REMATCH[2]}
#hostname=${BASH_REMATCH[3]}
user=${BASH_REMATCH[4]}
repo=$(basename -s .git "${BASH_REMATCH[5]}")
fi
project="$user/$repo"
pass_paths=()
pass_content=$(pass "ansible/$project")
if [ "$?" -ne 0 ]; then
echo "Error: failed to load ansible/$project from pass" >&2
exit 1
fi
grep_filter="^path:"
if [ -n "$target" ]; then
grep_filter="^path: $target$"
fi
while read -r pass_path; do
pass_paths+=("$pass_path")
done <<< "$(echo "$pass_content" | grep "$grep_filter" | cut -d' ' -f2-)"
case "$action" in
show)
echo "$pass_content" | head -n 1
exit 0 ;;
list)
echo "$pass_content" | grep "^path:" | cut -d' ' -f2-
exit 0 ;;
view)
ansible-vault view "${pass_paths[@]}"
exit 0 ;;
edit)
ansible-vault edit "${pass_paths[@]}"
exit 0 ;;
deploy)
pass show "ansible/$project.tar" | tar x
exit 0 ;;
save)
tar c "${pass_paths[@]}" | pass insert -m "ansible/$project.tar"
exit 0 ;;
pass-edit)
pass edit "ansible/$project"
exit 0 ;;
*)
echo "Usage: ansible-vault-manager [show|list|view|edit|deploy|save|pass-edit]"
exit 0 ;;
esac