Skip to content

Instantly share code, notes, and snippets.

@rleap-m
Last active September 24, 2024 20:24
Show Gist options
  • Save rleap-m/62c3cf95175d56a1b4c3a2b15b0d0c56 to your computer and use it in GitHub Desktop.
Save rleap-m/62c3cf95175d56a1b4c3a2b15b0d0c56 to your computer and use it in GitHub Desktop.
Gets the labels associated with each node
<#
.SYNOPSIS
Gets the labels associated with each node
.PARAMETER NodeName
Specify a single node (if not provided all nodes returned)
.PARAMETER Flatten
Flattens out the labels such that there is a node object returned per label
#>
[CmdletBinding()]
param (
[Parameter()]
[string]
$NodeName,
[switch] $Flatten
)
if ($NodeName) {
$nodes = @(kubectl get node $NodeName -o json | ConvertFrom-Json -ErrorAction Stop)
}
else {
$nodes = @((kubectl get nodes -o json | ConvertFrom-Json -ErrorAction Stop).items)
}
foreach ($node in $nodes) {
$rawLabels = ($node.metadata.labels | ConvertTo-Json -Compress).Trim('{','}') -split ','
$labels = foreach ($rawLabel in $rawLabels) {
$name,$value = $rawLabel.Split(':')
[pscustomobject]@{
'LabelName' = $name.Trim("""")
'LabelValue' = $value.Trim("""")
}
}
$roles = @($labels.LabelName -match 'node-role.kubernetes.io')
$roleNames = @(foreach ($role in $roles) {
($role -split '/')[1]
})
if ($roleNames.Count -eq 0) {
$roleNames = '<none>'
}
if ($Flatten) {
foreach ($label in $labels) {
[PSCustomObject]@{
NodeName = $node.metadata.name
Role = $roleNames
OS = $node.status.nodeInfo.operatingSystem
LabelName = $label.LabelName
LabelValue = $label.LabelValue
}
}
}
else {
[PSCustomObject]@{
NodeName = $node.metadata.name
Role = $roleNames
OS = $node.status.nodeInfo.operatingSystem
Labels = $labels
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment