Skip to content

Instantly share code, notes, and snippets.

@kaugm
Last active July 20, 2022 13:28
Show Gist options
  • Save kaugm/258bd1d8fb9d6cbb718019b64a4275b9 to your computer and use it in GitHub Desktop.
Save kaugm/258bd1d8fb9d6cbb718019b64a4275b9 to your computer and use it in GitHub Desktop.
Filter and pretty-print labels of Kubernetes Pods and Nodes for better reading and debugging
#!/opt/homebrew/bin/python3
''' Help: Ensure filter.py is executable -> 'chmod u+x filter.py'
Help: Ensure path to python executable is correct on first line -> 'which python3'
Help: filter.py -h '''
import re, sys, argparse
class KObject:
'''Kubernetes node or pod object'''
def __init__(self, line, object_type):
self.name = parse(line)['Name']
self.labels = parse(line)['Labels']
self.output = f" \n{object_type}: {self.name}\n\n"
def __str__(self):
for label in self.labels:
self.output += f'{label}\n'
self.output += '\n---'
return self.output
class Colors:
'''Color output in terminal. Extra colors for future use'''
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def parse(line):
'''Parses stdin with regex and returns data of type dictionary'''
# regex = '([a-zA-Z0-9\-\.\=\/]+,.+)'
regex = '([a-zA-Z0-9\-\.\/]+\=[a-zA-Z0-9\-\.\/]+,.+)'
id_regex = '^[^ ]*' # "Everything up until the first space"
labels = []
# Find object ID
object_id = re.findall(id_regex, line)[0]
# Split found labels chunk by ',' and add to list
for label in re.findall(regex, line)[0].split(','):
try:
if args.val in label:
labels.append(f'{Colors.FAIL}{label}{Colors.ENDC}')
else:
labels.append(label)
except:
labels.append(label)
return {'Name':object_id, 'Labels':labels}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Pretty print & filter node and pod labels. Usage: kubectl get [nodes|pods] --show-labels | ./filter.py -v <value>')
parser.add_argument('-v', '--val', help='Specify a value [string] to filter by')
args = parser.parse_args()
# Read in stdin
stdin = sys.stdin
# First line saved to identify k8s object type, later
stdin_first_line = stdin.readline()
# Continue to lines 2+
# next(stdin)
# Prevent errors if argument not specified
try: args.val
except: NameError: args.val = None
# Each line of stdin is a separate kubernetes object that must be parsed
i = 0
for line in stdin:
# First line of stdin has column titles to differentiate object type
if 'NODES' in stdin_first_line:
kubernetes_object = KObject(line, "Node")
else:
kubernetes_object = KObject(line, "Pod")
# Only print objects that contain queried string in labels
if args.val is None:
print(kubernetes_object)
else:
if args.val in '\t'.join(kubernetes_object.labels):
print(kubernetes_object)
i += 1
if i == 0:
print(f'No occurences of {Colors.FAIL}{args.val}{Colors.ENDC} were found in output.')
@kaugm
Copy link
Author

kaugm commented Jul 20, 2022

Usage: kubectl get nodes | ./filter.py -v 'c5.large'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment