keep-rbac-yaml.sh 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env bash
  2. set -eEuo pipefail
  3. # READS FROM STDIN
  4. # WRITES TO STDOUT
  5. # DEBUGS TO STDERR
  6. : ${YQ:=yq}
  7. if [[ "$($YQ --version)" != "yq (https://github.com/mikefarah/yq/) version 4."* ]]; then
  8. echo "yq must be version 4.x"
  9. exit 1
  10. fi
  11. temp_dir="$(mktemp -d)"
  12. pushd "${temp_dir}" &>/dev/stderr
  13. # Output the RBAC into separate temporary files named with Kind and Name so that the filesystem can
  14. # sort the files, and we can keep the same resource ordering as before for easy diffing. Then we
  15. # just read in the files, sorted by the fs for final output.
  16. $YQ eval '
  17. select(.kind == "PodSecurityPolicy"),
  18. select(.kind == "ServiceAccount"),
  19. select(.kind == "ClusterRole"),
  20. select(.kind == "ClusterRoleBinding"),
  21. select(.kind == "Role"),
  22. select(.kind == "RoleBinding")
  23. ' - | # select all RBAC resource Kinds
  24. $YQ eval 'del(.metadata.labels."helm.sh/chart")' - | # remove the 'helm.sh/chart' label that only applies to Helm-managed resources
  25. $YQ eval 'del(.metadata.labels."app.kubernetes.io/managed-by")' - | # remove the 'labels.app.kubernetes.io/managed-by' label that only applies to Helm-managed resources
  26. $YQ eval 'del(.metadata.labels."app.kubernetes.io/created-by")' - | # remove the 'app.kubernetes.io/created-by' label that only applies to Helm-managed resources
  27. sed '/^$/d' | # remove empty lines caused by yq's display of header/footer comments
  28. sed '/^# Source: /d' | # helm adds '# Source: <file>' comments atop of each yaml doc. Strip these
  29. $YQ eval --split-exp '.kind + " " + .metadata.name + " "' - # split into files by <kind> <name> .yaml
  30. # outputting the filenames with spaces after kind and name keeps the same sorting from before
  31. RBAC_FILES=()
  32. while read -r line; do
  33. RBAC_FILES+=("$line")
  34. done < <(find . -type f -name '*.yml' | sort)
  35. # For debugging, output the resource kinds and names we processed and the number we are keeping
  36. #for file in "${RBAC_FILES[@]}"; do
  37. # basename to get rid of the leading './' which find adds; %.yml to remove the .yml suffix
  38. # basename "${file%.yml}" >/dev/stderr
  39. #done
  40. # shellcheck disable=SC2012 # we know filenames are alphanumeric from being k8s resources
  41. echo "Number of RBAC resources: ${#RBAC_FILES[@]}" >/dev/stderr
  42. $YQ eval-all '.' "${RBAC_FILES[@]}" | # output all files, now sorted by Kind and Name by the fs
  43. sed '/^$/d' # remove empty lines caused by yq's display of header/footer comments
  44. rm -rf "${temp_dir}"
  45. popd &>/dev/stderr