Skip to content

Instantly share code, notes, and snippets.

@meleu
Last active December 9, 2021 21:38
Show Gist options
  • Save meleu/ea242b9b1939eaeb5212a3cca1b87b65 to your computer and use it in GitHub Desktop.
Save meleu/ea242b9b1939eaeb5212a3cca1b87b65 to your computer and use it in GitHub Desktop.
List possible k8s Deployments and Services in the limbo.
#!/usr/bin/env bash
# limbo-k8s-components.sh
#########################
#
# Usage:
# ./limbo-k8s-components.sh [namespace]
#
# This script assumes all Deployment.spec.template.labels have an "app" label
# AND all Service.spec.selector are selecting an "app" label.
#
# The script gets a list of all "app" labels in template of all active
# deployments AND a list "app" labels in Services selectors.
#
# By comparing both lists its possible to infer which resources are in limbo,
# in other words, active but unused
#
# Augusto "meleu" Lopes
# https://github.com/meleu
#
# shellcheck disable=SC2155
readonly NAMESPACE="${1:-default}"
# getDeploymentsWithAppLabel()
# List all "app" labels being generated by all active deployments.
# arg1: namespace (optional)
getDeploymentsAppLabels() {
kubectl get deployments \
-n "${NAMESPACE}" \
-o jsonpath='{.items[*].spec.template.metadata.labels.app}' \
| tr ' ' '\n' \
| sort -u
}
# getServicesAppSelectors()
# List all "app" selectors currently in use by all active services.
getServicesAppSelectors() {
kubectl get services \
-n "${NAMESPACE}" \
-o jsonpath='{.items[*].spec.selector.app}' \
| tr ' ' '\n' \
| sort -u
}
main() {
local fileFromDeployments="$(mktemp)"
local fileFromServices="$(mktemp)"
echo -e "\nGetting data from the '${NAMESPACE}' namespace\n"
echo -n "Getting the list of app labels from Deployments templates..."
getDeploymentsAppLabels > "${fileFromDeployments}"
echo " DONE!"
echo -n "Getting the list of app labels from Services selectors..."
getServicesAppSelectors > "${fileFromServices}"
echo " DONE!"
echo -e "\n\n--> List of DEPLOYMENTS not bound to any Service:\n"
diff "${fileFromDeployments}" "${fileFromServices}" \
| grep '^<' \
| cut -d' ' -f2
echo -e "\n\n--> List of SERVICES not bound to any Deployment:\n"
diff "${fileFromDeployments}" "${fileFromServices}" \
| grep '^>' \
| cut -d' ' -f2
rm -f "${fileFromDeployments}" "${fileFromServices}"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment