Skip to content

Instantly share code, notes, and snippets.

@lalyos
Last active April 26, 2024 16:14
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lalyos/aef94a4c23973eaee4a17bb26b6972a2 to your computer and use it in GitHub Desktop.
Save lalyos/aef94a4c23973eaee4a17bb26b6972a2 to your computer and use it in GitHub Desktop.
k8s etcd list keys

You can demostrate how kubernetes stores everything in etcd (v3):

One-liner

You can exec etcdctl rigth in the etc pod:

kubectl exec -it \
  -n kube-system etcd-minikube \
  -- sh -c 'ETCDCTL_CACERT=/var/lib/localkube/certs/etcd/ca.crt \
    ETCDCTL_CERT=/var/lib/localkube/certs/etcd/peer.crt \
    ETCDCTL_KEY=/var/lib/localkube/certs/etcd/peer.key \
    ETCDCTL_API=3  \
    etcdctl \
      get \
      --keys-only \
      --prefix=true \
      "/registry/namespaces/" '

Proxy to etcd

Or if you have etcdctl installed on your host. You can run etcdctl command on your localhost.

Copy certificate and key from container to localhost:

kubectl cp kube-system/etcd-minikube:/var/lib/localkube/certs/etcd/peer.key .
kubectl cp kube-system/etcd-minikube:/var/lib/localkube/certs/etcd/peer.crt . 

Set ETCDCTL_ environment variables

export \
  ETCDCTL_API=3 \
  ETCDCTL_INSECURE_SKIP_TLS_VERIFY=true  \
  ETCDCTL_CERT=peer.crt \
  ETCDCTL_KEY=peer.key

Start a proxy (in a separate terminal) to be able to connect to etcd on localhost:

kubectl port-forward -n kube-system etcd-minikube 2379:2379
etcdctl  get --keys-only --prefix=true "/registry/namespaces/"
@eunsukimme
Copy link

Thanks!

btw, for who are using minikube, not localkube(cause it is deprecated), should replace terms localkube to minikube and it will work!

so above one-liner snippet will be:

kubectl exec -it \
  -n kube-system etcd-minikube \
  -- sh -c 'ETCDCTL_CACERT=/var/lib/minikube/certs/etcd/ca.crt \
    ETCDCTL_CERT=/var/lib/minikube/certs/etcd/peer.crt \
    ETCDCTL_KEY=/var/lib/minikube/certs/etcd/peer.key \
    ETCDCTL_API=3  \
    etcdctl \
      get \
      --keys-only \
      --prefix=true \
      "/registry/namespaces/" '

@fxshlein
Copy link

fxshlein commented Dec 4, 2021

Thank you!

Turned it into a small script for the super lazy people out there:

#!/bin/sh

PROFILE=$(minikube profile)
CMD="$@"

kubectl exec -it \
  -n kube-system "etcd-$PROFILE" \
  -- sh -c \
    "ETCDCTL_CACERT=/var/lib/minikube/certs/etcd/ca.crt \
    ETCDCTL_CERT=/var/lib/minikube/certs/etcd/peer.crt \
    ETCDCTL_KEY=/var/lib/minikube/certs/etcd/peer.key \
    ETCDCTL_API=3 \
    $CMD"

You can use it like this:
./scriptname etcdctl get --keys-only --prefix=true "/registry/namespaces/"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment