Skip to content

Instantly share code, notes, and snippets.

@xenji
Created August 16, 2019 08:30
Show Gist options
  • Select an option

  • Save xenji/b72a4be69ae6d9290ba2127a96347de1 to your computer and use it in GitHub Desktop.

Select an option

Save xenji/b72a4be69ae6d9290ba2127a96347de1 to your computer and use it in GitHub Desktop.

Revisions

  1. xenji created this gist Aug 16, 2019.
    37 changes: 37 additions & 0 deletions kubectx.ps1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    Param(
    [Parameter(Mandatory = $false, Position = 0)]
    [string]$name
    )

    function current_context() {
    kubectl config view -o=jsonpath='{.current-context}'
    }

    function get_contexts() {
    kubectl config get-contexts -o=name | Sort-Object
    }

    function list_contexts() {
    $gctx = (get_contexts)
    $cur = (current_context)

    ForEach ($i in $gctx) {
    if ($i -eq $cur) {
    Write-Host "*" $i -ForegroundColor Red
    }
    else {
    Write-Host $i
    }
    }
    }

    function switch_context($context) {
    kubectl config use-context $context
    }

    if (![string]::IsNullOrEmpty($name)) {
    switch_context $name
    }
    else {
    list_contexts
    }
    50 changes: 50 additions & 0 deletions kubens.ps1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    Param(
    [Parameter(Mandatory = $false, Position = 0)]
    [string]$name
    )

    function currentContext() {
    return kubectl config current-context
    }

    function getNamespace() {
    Param(
    [Parameter(Mandatory = $false, Position = 0)]
    [string]$name
    )
    return kubectl config view -o=jsonpath="{.contexts[?(@.name=='${name}')].context.namespace}"
    }

    function setNamespace() {
    Param(
    [Parameter(Mandatory = $false, Position = 0)]
    [string]$name
    )
    $cur = currentContext
    $ret = kubectl config set-context "$cur" --namespace="${name}"
    Write-Host $ret
    if ($LASTEXITCODE -eq 0) {
    Write-Host "Switched to namespace $name"
    }
    }


    function listNamespaces() {
    $cur = getNamespace(currentContext)
    [string]$namespaces = (kubectl get namespaces -o=jsonpath="{range .items[*].metadata.name}{@}{','}{end}")
    $nsList = $namespaces.Split(",")
    ForEach ($i in $nsList) {
    if ($i -eq $cur) {
    Write-Host "*" $i -ForegroundColor Red
    }
    else {
    Write-Host $i
    }
    }
    }
    if (![string]::IsNullOrEmpty($name)) {
    setNamespace $name
    }
    else {
    listNamespaces
    }