-
Notifications
You must be signed in to change notification settings - Fork 0
/
vedit
executable file
·90 lines (75 loc) · 2.54 KB
/
vedit
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
88
89
90
#!/usr/bin/env bash
if [[ $BASH_VERSION != 5.* ]]; then
echo >&2 "ERROR: This script requires bash version 5"
echo >&2 "Run: brew install bash"
exit 1
fi
set -Eeuo pipefail
shopt -s inherit_errexit
export createSecretOption="Create new secret"
function get_vault_path() {
local path
path="${1:-}"
upADir="../ (up a directory)"
while [[ $path =~ /$ ]]; do
new_path=$(
vault kv list -format=json "${path}" |
jq --arg createSecret "$createSecretOption" --arg upADir "$upADir" -r '[ $upADir, $createSecret ] + . | .[]' |
fzf --prompt="Path: ${path}" --preview="
if [[ {} == '$createSecretOption' ]]; then
echo 'Create new secret...'
elif [[ {} =~ /$ ]]; then
vault kv list -format=table '${path}{}'
else
vault kv get -format=table '${path}{}'
fi"
)
if [[ ${new_path} == "$upADir" ]]; then
up_path="$(dirname "$path")/"
if [[ $up_path != "./" ]]; then
path="$up_path"
fi
else
path="${path%/}/${new_path}"
fi
done
echo "$path"
}
function main() {
if ! vault token lookup; then
echo >&2 "ERROR: Vault token not found"
echo >&2 "You can login with: vault login -method=ldap username=SSO_USERNAME"
exit 1
fi
local path
path=$(get_vault_path "${1:-${VEDIT_DEFAULT_KV_PATH:-secret/}}")
if [[ ${path##*/} == "$createSecretOption" ]]; then
read -p "Enter the new secret name: ${path%/*}/" new_secret
path="${path%/*}/${new_secret}"
if ! vault kv get "$path" >/dev/null; then
echo >&2 "Creating new secret: ${path}"
vault kv put "${path}" placeholder="delete-this" >/dev/null
else
echo >&2 "ERROR: Secret already exists: ${path}"
fi
fi
content=$(vault kv get -format=json "${path}" | jq -r '.data.data' | yq -P -o yaml)
tmpfile=$(mktemp --suffix=.yaml)
echo >&2 "Editing at: ${tmpfile}"
echo "${content}" >"${tmpfile}"
if ! "${EDITOR:=vim}" "${tmpfile}"; then
echo >&2 "ERROR: ${EDITOR} did not exit cleanly"
exit 1
fi
new_content=$(cat "${tmpfile}")
if [[ "${new_content}" == "${content}" ]]; then
echo >&2 "No changes detected, exiting"
exit 0
fi
cat "${tmpfile}" | yq -o json . | vault kv put "${path}" @/dev/stdin
echo >&2
echo >&2 "Updated path: ${path}"
echo >&2
vault kv get "${path}"
}
main "${@}"