Last active
February 27, 2019 23:48
-
-
Save triangletodd/8a5b610a76b6fdfbc451d1b09c7bf8dd to your computer and use it in GitHub Desktop.
Create a PDB for all deployments in the default Kubernetes namespace with a minAvailable of 50%
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -e | |
template() { | |
cat <<EOF | |
apiVersion: policy/v1beta1 | |
kind: PodDisruptionBudget | |
metadata: | |
name: {{NAME}} | |
namespace: default | |
spec: | |
minAvailable: 50% | |
selector: | |
matchLabels: | |
app: {{APP_SELECTOR}} | |
{{TIER_SELECTOR}} | |
EOF | |
} | |
deployments() { | |
kubectl get deployment -o json \ | |
| jq -r '.items [] | .metadata | .name + "," + .labels.app + "," + .labels.tier' | |
} | |
pod_count() { | |
local count=$( \ | |
kubectl get deployment "$1" -o json \ | |
| jq '.status.replicas' \ | |
) | |
if [[ $count == "" ]]; then | |
echo 0 | |
else | |
echo $count | |
fi | |
} | |
render() { | |
if [[ $# -lt 2 ]] || [[ $# -gt 3 ]]; then | |
echo "$@" | |
exit 1 | |
fi | |
NAME="$1" | |
APP_SELECTOR="$2" | |
TIER_SELECTOR="" | |
if [[ -n "$3" ]]; then | |
TIER_SELECTOR="tier: $3" | |
fi | |
sed -e 's/{{NAME}}/'"$NAME"'/' \ | |
-e 's/{{APP_SELECTOR}}/'"$APP_SELECTOR"'/' \ | |
-e 's/{{TIER_SELECTOR}}/'"$TIER_SELECTOR"'/' <<< $(template) | |
} | |
main() { | |
kubectl delete pdb --all | |
for i in $(deployments); do | |
IFS=, read name app_selector tier_selector <<< $i | |
if [[ $(pod_count $name) -lt 2 ]]; then | |
continue | |
fi | |
render $name $app_selector $tier_selector \ | |
| kubectl create -f - | |
done | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment