truestuff/kube-get-secrets.sh

136 lines
3.2 KiB
Bash
Executable File

#! /usr/bin/env bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
USER_HOME=$HOME
[[ -n "${SUDO_USER}" ]] && USER_HOME="$(eval "echo ~${SUDO_USER}")"
. ${SHRC_D:-$SCRIPT_DIR}/01_util.functions
set -e
JSON=0
if [[ " $* " =~ " --help " ]]; then
cat <<USAGE
Usage:
./kube-get-secrets.sh --help
sudo ./kube-get-secrets.sh [--json]
Description:
USAGE
exit 0
fi
ARGS=()
ARGS_MODE=1
ALL=0
while [[ -n "$1" ]]; do
if [[ "$ARGS_MODE" -eq 1 && "$1" =~ ^-- ]]; then
case "$1" in
"--json")
JSON=1
;;
"--force")
ALL=1
;;
"--")
ARGS_MODE='--'
;;
*)
ARGS=("${ARGS[@]}" "$1")
esac
else
ARGS=("${ARGS[@]}" "$1")
fi
shift
done
# require_root
QUERY_NAMESPACE=' -A'
[[ ${#ARGS[@]} -eq 0 ]] || QUERY_NAMESPACE=$( printf -- ' --namespace=ix-%s' "${ARGS[@]}" )
jqcode='
.items[] | select(.metadata.name|test("."))
| {
"name": .metadata.namespace,
"app": (
if .metadata.labels."app.kubernetes.io/instance" != null then
.metadata.labels."app.kubernetes.io/instance"
else
.metadata.labels."cnpg.io/cluster"
end
),
,"data":
,"raw": .
} | {
"name": .name,
"app": .app,
"url": (
if (.url|type) == "object" then
""
else
.url
end
),
"data": (
if (.url|type) == "object" then
.url
else
.url |
match("(.*)://(.+):(.+)@([^:]+)(:(\\d+))?/(.*)$") | .captures | {
"protocol": .[0].string,
"username": .[1].string,
"password": .[2].string,
"passwordlen": .[2].string | length,
"host": .[3].string,
"safeport": .[4].string,
"port": .[5].string,
"dbname": .[6].string,
}
end
)
} | {
"name": .name,
"raw_url": .url,
"url": "\(.data.protocol)://\(.data.username)@\(.data.password):\(.data.host).\(.name).svc.cluster.local\(.data.safeport)/\(.data.dbname)",
"safeurl": "\(.data.protocol)://\(.data.username)@*******:\(.data.host).\(.name).svc.cluster.local\(.data.safeport)/\(.data.dbname)",
"protocol": .data.protocol,
"username": .data.username,
"password": .data.password,
"pwd_len": .data.passwordlen,
"host": "\(.data.host).\(.name).svc.cluster.local",
"port": .data.port,
"dbname": .data.dbname
}
'
[[ "$ALL" -eq 1 ]] || jqcode="$jqcode | select( .raw_url != \"\" )"
json_results="$(
<<<"${QUERY_NAMESPACE}" \
xargs -n1 k3s kubectl \
get secrets \
--output json \
| jq "$jqcode"
)"
[[ "$JSON" -eq 1 ]] && echo "$json_results" && exit 0
JQ_COLS="[$( <<<"\"$TCDBCOLS\"" \
jq -r '. | split(",") | map( "\"\(.)\"" ) | join(",")'
)]"
JQ_COLS_REGEX="$( <<<"$JQ_COLS" \
jq -r '. | map ( ".\(.)" ) | join(",")'
)"
[[ -z "$NOHEAD" ]] || JQ_COLS=
jqcode='
['"${JQ_COLS^^}"'] + [.[] |
['"$JQ_COLS_REGEX"']
] | .[] | join("|")
'
<<<"$json_results" jq -s '.' | jq -r "$jqcode" | column -t -s "|"
exit 0