Skip to content

Instantly share code, notes, and snippets.

@forsberg
Created May 23, 2019 13:14
Show Gist options
  • Select an option

  • Save forsberg/6011f156d2f2d1a1577271640ba1ccac to your computer and use it in GitHub Desktop.

Select an option

Save forsberg/6011f156d2f2d1a1577271640ba1ccac to your computer and use it in GitHub Desktop.
Python snippet to sort a multi-document YAML file
#!/usr/bin/env python
# Script for sorting Kubernetes multi-manifest files
# Can be used when you need to compare e.g. a static yaml manifest, and
# what comes out of a helm chart.
#
# Run pip install yaml before trying to run this script
# ./sort-yaml.py < manifest.yaml
# Copyright 2018 NIRA Dynamics AB.
# SPDX-License-Identifier: Apache-2.0
import sys
import yaml
docs = yaml.load_all(sys.stdin.read(), Loader=yaml.SafeLoader)
docs = [doc for doc in docs if doc is not None]
sorted_docs = sorted(docs, key=lambda x: f"{x['kind']}/{x['metadata']['name']}")
print(yaml.dump_all(sorted_docs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment