Created
August 16, 2019 08:30
-
-
Save xenji/b72a4be69ae6d9290ba2127a96347de1 to your computer and use it in GitHub Desktop.
Naive and simple kubectx and kubens implementations for Powershell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment