Kubernetes Context & Namespace Switcher For PowerShell, Works Like A Charm

Jung-Hyun Nam
Mar 9 · 2 min read
Image for post
Image for post
https://unsplash.com/photos/aYHzEnSEH-w

If you are stick with Kubernetes every day, you may know or consider shorthand expression of the kubectl.

I’m using the alias K, kubectx and kubens every day. But these scripts are not designed for PowerShell. So I tried to make the own version of each shorthand convention. Naturally, you can use below snippets to your other environments, including Windows.

Requirements

These modules require the PSFzf module and fzf binary for your operating system.

The “K” Alias

Set-Alias k kubectl

The “Select-KubeContext” (a.k.a. kubectx)

function global:Select-KubeContext {
[CmdletBinding()]
[Alias('kubectx')]
param (
[parameter(Mandatory=$False,Position=0,ValueFromRemainingArguments=$True)]
[Object[]] $Arguments
)
begin {
if ($Arguments.Length -gt 0) {
$ctx = & kubectl config get-contexts -o=name | fzf -q @Arguments
} else {
$ctx = & kubectl config get-contexts -o=name | fzf
}
}
process {
if ($ctx -ne '') {
& kubectl config use-context $ctx
}
}
}

The “Select-KubeNamespace” (a.k.a. kubens)

function global:Select-KubeNamespace {
[CmdletBinding()]
[Alias('kubens')]
param (
[parameter(Mandatory=$False,Position=0,ValueFromRemainingArguments=$True)]
[Object[]] $Arguments
)
begin {
if ($Arguments.Length -gt 0) {
$ns = & kubectl get namespace -o=name | fzf -q @Arguments
} else {
$ns = & kubectl get namespace -o=name | fzf
}
}
process {
if ($ns -ne '') {
$ns = $ns -replace '^namespace/'
& kubectl config set-context --current --namespace=$ns
}
}
}

Paste these codes to your $PROFILE script code and restart the shell. Then you will get a more comfortable PowerShell workspace for your daily DevOps works.

Beyond the Windows

DevOps Engineer’s Blog

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store