Moving the Credentials in a Local kubeconfig into 1Password
kubectl connects to a cluster by reading a kubeconfig such as ~/.kube/config. The kubeconfig holds the private key of the client certificate or a token in plain text. Because the file sits in the home directory, it gets copied into backups, and any process running as the same user can read it. In an environment where AI agents work on repositories, an agent may read the file as well.
This article describes how to take only the credentials out of the kubeconfig, keep them in 1Password, and fetch them with the 1Password CLI (op) when kubectl runs. It includes the contents and usage of the two scripts written for this.
op-kube-credential: called by kubectl; reads the credentials from 1Password and returns themkubeconfig-to-op: rewrites an existing kubeconfig so that it usesop-kube-credential
Which parts of a kubeconfig are secret
A kubeconfig mixes secret and non-secret values.
| Field | Secret? |
|---|---|
clusters[].cluster.server |
No |
clusters[].cluster.certificate-authority-data |
No (the cluster's CA certificate) |
users[].user.client-certificate-data |
No (the client certificate) |
users[].user.client-key-data |
Yes (the private key of the client certificate) |
users[].user.token |
Yes |
A certificate is the public half of a key pair, so it is not a problem if someone reads it. kubectl uses certificate-authority-data to check that the API server it connects to is the real one. The risk with this value is not that it is read but that it is replaced, and replacing it requires write access to the home directory.
Only the users section needs to move to 1Password.
Choosing an approach
There are several ways to keep a kubeconfig in 1Password.
- Keep the whole kubeconfig in 1Password and pass it through process substitution, as in
KUBECONFIG=<(op inject -i template) - Write the kubeconfig to a temporary file on each run and delete it afterwards
- Keep the kubeconfig on disk and replace only
userswith an exec credential plugin
With option 1, the file created by process substitution can be read only once. k9s and kubectl config use-context write to the kubeconfig, so they do not work with this approach. With option 2, a crash or Ctrl-C leaves the plaintext file behind.
I chose option 3. An exec credential plugin is a standard kubectl mechanism: kubectl runs the command written in users[].user.exec and reads the credentials from its standard output. No secret remains in the kubeconfig, so it does not matter when switching contexts writes to the file.
After the rewrite, users looks like this.
users:
- name: admin
user:
exec:
apiVersion: client.authentication.k8s.io/v1
interactiveMode: Never
command: op-kube-credential
args:
- op://development/kubeconfig-example/cluster-a-user
The value passed in args is a 1Password secret reference (op://<vault>/<item>/<field>). interactiveMode: Never tells kubectl that the plugin does not use standard input.
Shell expansion does not apply to command. kubectl runs the command without a shell, so ~ and ${HOME} stay as literal strings. There are two alternatives.
- If the value contains a
/, as in./op-kube-credential, it is a path relative to the directory of the kubeconfig file - If it contains no
/, as inop-kube-credential, kubectl looks it up inPATH
Here the script is placed in a directory on PATH and referred to by name only.
Format stored in 1Password
An exec credential plugin writes JSON called ExecCredential to standard output.
{
"apiVersion": "client.authentication.k8s.io/v1",
"kind": "ExecCredential",
"status": {
"clientCertificateData": "-----BEGIN CERTIFICATE-----\n...",
"clientKeyData": "-----BEGIN EC PRIVATE KEY-----\n..."
}
}
For token authentication, status contains token instead.
I decided to store only the status part, as YAML, in a 1Password field. A single op read call is enough, which is faster than keeping the certificate and key in separate fields. Storing it as JSON would require writing the PEM line breaks as \n, which is hard to read in 1Password.
status:
clientCertificateData: LS0tLS1CRUdJTi...
clientKeyData: LS0tLS1CRUdJTi...
In a kubeconfig, client-certificate-data and client-key-data are PEM encoded in base64. In an ExecCredential, on the other hand, clientCertificateData and clientKeyData take the PEM as is. If the kubeconfig values are passed through unchanged, kubectl stops with this error.
Unable to connect to the server: getting credentials: failed parsing client key/certificate: tls: failed to find any PEM data in certificate input
To save the effort of converting values copied from the kubeconfig, 1Password stores them in base64 and op-kube-credential decodes them. A token is plain text in the kubeconfig too, so it is not decoded.
op-kube-credential
#!/bin/zsh
# kubeconfig の認証情報を 1password から読み込むためのスクリプト
set -eu
# kubectl を Dock 起動のアプリ等から呼ばれると Homebrew が PATH に無い
PATH=/opt/homebrew/bin:/usr/local/bin:$PATH
# 1Password には kubeconfig の *-data の値 (base64) をそのまま保存しているが、
# ExecCredential は生の PEM を要求する。token は kubeconfig でも平文なので戻さない。
# 無いフィールドに @base64d を当てると壊れた値が作られるので、有る時だけ変換する
op read "$1" | yq -o=json '
with(.status | select(has("clientCertificateData"));
.clientCertificateData |= @base64d
| .clientKeyData |= @base64d)
| . + {
"apiVersion": "client.authentication.k8s.io/v1",
"kind": "ExecCredential"
}'
The YAML taken out with op read is converted to JSON with mikefarah's yq. (The comments in the script are in Japanese.)
with(.status | select(has("clientCertificateData")); ...)applies@base64donly when a certificate is present. Applying@base64dto a missing field makes yq create a corruptedclientCertificateData, and a token-only setup stops working- The script adds
apiVersionandkind, so onlystatusneeds to be stored in 1Password - When kubectl is called from an app launched from the Dock or similar,
PATHdoes not include the Homebrew directories. The script setsPATHat the top so thatopandyqare found
Do not use set -x or any logging inside the script. kubectl prints the plugin's standard error to the terminal, which would show the credentials.
kubeconfig-to-op
Rewriting an existing kubeconfig by hand makes it easy to get the rename or the overwrite wrong. So I wrote a script that does the following in one go.
- Show what will be changed, and continue only when
yis entered - Rename the original kubeconfig to
<kubeconfig>.backup.YYYYmmdd - Write a kubeconfig under the original name with
usersreplaced by the exec credential plugin - Print the YAML to paste into the 1Password field to standard output
kubeconfig-to-op ~/.kube/config-cluster-a op://development/kubeconfig-example/cluster-a-user
When run, it first shows this confirmation. The confirmation and messages go to standard error; standard output carries only the YAML to paste into 1Password.
This will:
1. Rename /Users/me/.kube/config-cluster-a
-> /Users/me/.kube/config-cluster-a.backup.20261117
2. Write /Users/me/.kube/config-cluster-a (credentials removed)
3. Print the credentials to stdout for these 1Password fields:
user 'admin' -> op://development/kubeconfig-example/cluster-a-user
Proceed? [y/N]
After y is entered, it rewrites the files and prints commands for testing and the YAML.
Done. The backup still has the plaintext credentials: /Users/me/.kube/config-cluster-a.backup.20261117
Save the credentials below to 1Password, then test with:
KUBECONFIG=~/.kube/config-cluster-a kubectl auth whoami
KUBECONFIG=~/.kube/config-cluster-a kubectl get pods --all-namespaces
# ===== 1Password: op://development/kubeconfig-example/cluster-a-user =====
status:
clientCertificateData: LS0tLS1CRUdJTi...
clientKeyData: LS0tLS1CRUdJTi...
Paste this YAML into the 1Password field, then check the connection with the commands shown.
If the second argument stops at op://<vault>/<item>, the user name in the kubeconfig becomes the field name. Use this form for a kubeconfig with more than one user to convert.
kubeconfig-to-op ~/.kube/config op://development/kubeconfig-example
#!/usr/bin/env zsh
# kubeconfig の users からクライアント証明書・token を抜き、op-kube-credential で
# 1Password から読む形に書き換える。
#
# 確認 (y/N) のあとで次を行う。
# 1. 元のファイルを <kubeconfig>.backup.YYYYmmdd に改名する
# 2. 元の名前で、認証情報を抜いた kubeconfig を書く
# 3. 1Password のフィールドに貼る YAML (秘密鍵や token) を標準出力に出す
#
# 使い方:
# kubeconfig-to-op.sh <kubeconfig> <op://development/kubeconfig-XXX/YYY-user>
#
# kubeconfig-to-op.sh ~/.kube/config-cluster-a op://development/kubeconfig-example/cluster-a-user
#
# フィールドを省いて op://<vault>/<item> だけを渡すと、kubeconfig の user 名を
# フィールド名に使う。フィールドまで書けるのは、書き換え対象の user が
# 1 つの時だけ。
set -eu
die() {
echo "error: $*" >&2
exit 1
}
if (( $# != 2 )); then
echo "usage: ${0:t} <kubeconfig> <op://development/kubeconfig-XXX/YYY-user>" >&2
exit 1
fi
KUBECONFIG_PATH="$1"
OP_REF="${2%/}"
BACKUP_PATH="$KUBECONFIG_PATH.backup.$(date +%Y%m%d)"
[[ -L "$KUBECONFIG_PATH" ]] && die "$KUBECONFIG_PATH is a symlink. Pass the real file."
[[ -f "$KUBECONFIG_PATH" ]] || die "not found: $KUBECONFIG_PATH"
# 同じ日に 2 回実行すると、平文のバックアップを書き換え後のファイルで潰してしまう
[[ -e "$BACKUP_PATH" ]] && die "backup already exists: $BACKUP_PATH"
if [[ "$OP_REF" == op://*/*/* ]]; then
export OP_ITEM="${OP_REF%/*}"
export OP_FIELD="${OP_REF##*/}"
elif [[ "$OP_REF" == op://*/* ]]; then
export OP_ITEM="$OP_REF"
export OP_FIELD=""
else
die "the op reference must look like op://<vault>/<item>/<field>: $OP_REF"
fi
# kubeconfig に埋め込まれた証明書と token だけを対象にする。
# ファイルパス指定 (client-key / tokenFile) や username/password は対象外
HAS_CERT='((.user | has("client-certificate-data")) and (.user | has("client-key-data")))'
HAS_CRED="($HAS_CERT or (.user | has(\"token\")))"
SELECT="select($HAS_CRED)"
users=("${(@f)$(yq ".users[] | $SELECT | .name" "$KUBECONFIG_PATH")}")
users=(${users:#})
(( ${#users} > 0 )) || die "no user has client-certificate-data / client-key-data or token"
if [[ -n "$OP_FIELD" ]] && (( ${#users} > 1 )); then
die "several users to convert (${users[*]}). Pass only op://<vault>/<item> so each user gets its own field."
fi
# yq の select の中では `| not` が効かないので `== false` で比べる
skipped=("${(@f)$(yq ".users[] | select($HAS_CRED == false and (.user | has(\"exec\")) == false) | .name" "$KUBECONFIG_PATH")}")
skipped=(${skipped:#})
if [[ -n "$OP_FIELD" ]]; then
field_expr='strenv(OP_FIELD)'
else
field_expr='$name'
fi
# 確認より前に変換まで済ませておき、yq が失敗してもファイルに触れていない状態で止める
converted=$(yq "(.users[] | $SELECT) |= (.name as \$name | .user = {
\"exec\": {
\"apiVersion\": \"client.authentication.k8s.io/v1\",
\"interactiveMode\": \"Never\",
\"command\": \"op-kube-credential\",
\"args\": [strenv(OP_ITEM) + \"/\" + $field_expr]
}
})" "$KUBECONFIG_PATH")
{
echo "This will:"
echo " 1. Rename $KUBECONFIG_PATH"
echo " -> $BACKUP_PATH"
echo " 2. Write $KUBECONFIG_PATH (credentials removed)"
echo " 3. Print the credentials to stdout for these 1Password fields:"
for name in $users; do
echo " user '$name' -> $OP_ITEM/${OP_FIELD:-$name}"
done
for name in $skipped; do
echo " Skip user '$name' (no embedded certificate or token)"
done
} >&2
# 標準出力をリダイレクトされていても、確認は端末から読む
read -r "answer?Proceed? [y/N] " < /dev/tty || answer=""
[[ "$answer" == [yY] ]] || { echo "Aborted." >&2; exit 1; }
tmp_path=$(mktemp "$KUBECONFIG_PATH.XXXXXX")
trap 'rm -f "$tmp_path"' EXIT
print -r -- "$converted" > "$tmp_path"
chmod 600 "$tmp_path"
mv "$KUBECONFIG_PATH" "$BACKUP_PATH"
mv "$tmp_path" "$KUBECONFIG_PATH"
kubeconfig_display="${${KUBECONFIG_PATH:A}/#$HOME/~}"
{
echo "Done. The backup still has the plaintext credentials: $BACKUP_PATH"
echo
echo "Save the credentials below to 1Password, then test with:"
# whoami は RBAC の権限が無くても認証さえ通れば成功するので、1Password からの
# 読み込みの確認に向く。1.27 未満のクラスタでは使えないので get pods も出す
echo " KUBECONFIG=$kubeconfig_display kubectl auth whoami"
echo " KUBECONFIG=$kubeconfig_display kubectl get pods --all-namespaces"
} >&2
for name in $users; do
echo
echo "# ===== 1Password: $OP_ITEM/${OP_FIELD:-$name} ====="
USER_NAME="$name" yq ".users[] | select(.name == strenv(USER_NAME)) | {
\"status\": (
(select($HAS_CERT) | {
\"clientCertificateData\": .user[\"client-certificate-data\"],
\"clientKeyData\": .user[\"client-key-data\"]
}) // {}
) + (
(select(.user | has(\"token\")) | {\"token\": .user.token}) // {}
)
}" "$BACKUP_PATH"
done
Users that are converted
Only users with an embedded certificate (client-certificate-data and client-key-data) or token are rewritten. The following users are left as they are, and the confirmation screen shows Skip for them.
- Users that point to a certificate or token by file path (
client-key,tokenFile) - Users that authenticate with
usernameandpassword
Users that already authenticate with exec (such as aws eks get-token for EKS) have no secret in the kubeconfig, so they are left as they are without a message.
Safeguards against a failed rewrite
- It stops if a file with the backup name already exists. Running it twice on the same day would otherwise overwrite the plaintext backup from the first run with the rewritten file
- The rewritten content is generated before the confirmation. If yq fails, the script stops without touching any file
- The new kubeconfig is written to a temporary file and then moved to the original name, with permissions set to
600 - The confirmation input is read from
/dev/tty, so the prompt appears in the terminal even when standard output is redirected. Without a terminal, it stops withAborted. - Symbolic links are rejected, because renaming would move only the link
Test commands
The first command shown at the end is kubectl auth whoami.
kubectl get pods --all-namespacesneeds permission (RBAC) to list Pods in every namespace. With a restricted token it fails withForbiddeneven when authentication succeededkubectl versionandkubectl cluster-infoare not suited to checking authentication. Many clusters answer/versionwithout authenticationkubectl auth whoamireturns your user name as long as authentication succeeds, even without any permissions
auth whoami requires Kubernetes 1.27 or later, so get pods is shown as well for older clusters.
After the migration
What this approach protects is the file on disk. It helps against copies in backups, a stolen disk, and tools that scan files. When the 1Password CLI is integrated with the desktop app, an authorization lasts for a while per terminal session. During that time, any process in the same session can call op read, so a malicious process that is already running is not stopped.
op runs on every kubectl call, which adds about 0.5 to 1 second each time. In deployment scripts that call kubectl many times, the delay adds up. Opening a new terminal, or leaving it idle for a while, brings up the 1Password authorization (Touch ID) again.
The backup created by kubeconfig-to-op still contains the plaintext credentials and needs to be deleted once the connection is confirmed. Backups such as Time Machine also hold the kubeconfig from before the migration. To keep the credentials from being read from them, issue a new client certificate or token and replace the value in 1Password. Kubernetes has no way to revoke a single client certificate, so a certificate has to be reissued. Most tokens written directly in a kubeconfig are ServiceAccount tokens without an expiry, so those should be recreated as well.
An unresolved case
On one k3s cluster, the following error appeared after the rewrite.
$ kubectl auth whoami
error: You must be logged in to the server (Unauthorized)
If the key and certificate did not match, kubectl would stop before connecting with private key does not match public key. A failed op read would also give a different error, getting credentials: exec: .... Here the request reached the server and Unauthorized came back, which means kubectl received a matching certificate and key from 1Password and the server rejected the certificate.
There are two candidate causes.
- An expired certificate. k3s client certificates are valid for one year, and restarting k3s when the expiry is near regenerates the certificates on the server. A kubeconfig copied to a local machine stays as it was, so it expires after a year
- A certificate from a different cluster was stored in 1Password
Checking whether the backup kubeconfig also gets Unauthorized, and whether the certificate's notAfter is in the past, would separate the two. This case has not been checked yet.
We look forward to discussing your development needs.