Skip to content

Instantly share code, notes, and snippets.

@duboisf
Created May 17, 2019 13:00
Show Gist options
  • Save duboisf/df120beeb6814b8a26cee2ae9cd178c6 to your computer and use it in GitHub Desktop.
Save duboisf/df120beeb6814b8a26cee2ae9cd178c6 to your computer and use it in GitHub Desktop.
Safely store a username and password for kubectl using pass
#!/bin/bash
# This script is intented to be used with kubectl when you don't want a plain
# base64 encoded username:password token in your kube config.
# It uses pass (https://www.passwordstore.org/) to store your password securely.
#
# To use it, download this script, make it executable (chmod +x
# safe_userpass_token) move it to the ~/.kube/bin folder (create it if it
# doesn't exist) and configure an entry in your ~/.kube/config under users,
# like so:
#
# ...
# users:
# ...
# - name: my_username_password
# user:
# exec:
# apiVersion: client.authentication.k8s.io/v1beta1
# args:
# - my_username
# - pass_name_in_pass
# command: ./bin/safe_userpass_token
# env: null
#
# and use it elsewhere in your ~/.kube/config:
#
# ...
# contexts:
# ...
# - context:
# cluster: some-cluster
# namespace: default
# user: my_username_password
if ! command -v pass > /dev/null 2>&1; then
echo "$0: You need to install pass (https://www.passwordstore.org/) to use this script." >&2
exit 1
fi
if ! command -v base64 > /dev/null 2>&1; then
echo "$0: You need the base64 binary to use this script." >&2
exit 1
fi
if (( $# != 2 )); then
cat >&2 <<EOF
USAGE: $0 USERNAME PASS_NAME
WHERE
USERNAME your username
PASS_NAME the name of the password in pass (https://www.passwordstore.org/)
EOF
exit 1
fi
USERNAME=$1
# The password name in pass (https://www.passwordstore.org/)
PASS_NAME="$2"
PASSWORD=$(pass "$PASS_NAME")
EXIT_CODE=$?
if (( $EXIT_CODE != 0 )); then
echo "$0: failed to get password from pass" >&2
exit $EXIT_CODE
fi
enable echo
TOKEN=$(echo -n "${USERNAME}:${PASSWORD}" | base64 -w0)
cat <<EOF
{
"apiVersion": "client.authentication.k8s.io/v1beta1",
"kind": "ExecCredential",
"status": {
"token": "$TOKEN"
}
}
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment