Use FZF to Speed Up KUBECTL

FZF is general purpose option selector for Linux command line. By default fzf is an super-upgrade for the ctrl-r command history finder, but it is helpful for almost any scenario where you need to pick 1 item from a list.

Here’s a tiny use case where I use fzf to select a kubernetes namespace and set it as the default namespace, just to save the effort to type --namespace flag everytime when I need to do something not in the default namespace.

#!/bin/bash
function kns() {
cns=$(kubectl get namespaces --output=jsonpath='{range .items[*]}{.metadata.name}{"\n"}'|fzf)
kubectl config set-context --current --namespace=$cns
}

Let me explain the script above step by step:

  1. kubectl get namespaces will list all namespaces currently accessible
  2. --output=jsonpath='{range .items[*]}{.metadata.name}{"\n"}' will only output the name of namespaces and 1 in each line
  3. |fzf to pipe the result from step 2 to fzf, a list will popup and becomes interactive for the user to choose one.
  4. kubectl config set-context --current --namespace=$cns will set the chosen namespace from step 3 as the default namespace

This is very convenient when there are not too many namespaces and when you need to work in different namespaces randomly. 🙂

2 Replies to “Use FZF to Speed Up KUBECTL”

  1. 在我印象中,2011年我开始建立博客的时候有一个叫raynix的博客。后来我的博客倒闭了,但您的博客我一直记得。前几年我又回来了,这个月又换了新域名。您的博客我越来越看不懂了,哈哈。您貌似已经移民到澳大利亚了吧,我看到了您的推特。

Leave a Reply to admin Cancel reply

Your email address will not be published. Required fields are marked *