Last active
July 31, 2024 14:03
-
-
Save achetronic/732cf006b2c41ca07dcb6ad985a9f0bd to your computer and use it in GitHub Desktop.
Put Helm annotations and labels on already deployed Kubernetes resources to adopt them inside a Helm Release automatically
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
#!/bin/bash | |
LOCAL_EXIT_CODE=0 | |
RELEASE_NAME="istiod" | |
RELEASE_NAMESPACE="istio-system" | |
HELM_CHART_PATH="./istio/istiod" | |
HELM_EXTRA_VALUES_PATH="./istio/common/istio.yaml" | |
# Get a JSON with the resources potentially adopted by this release | |
RESOURCES_TO_ADOPT_JSON=$(helm template "${RELEASE_NAME}" --namespace "${RELEASE_NAMESPACE}" --create-namespace "${HELM_CHART_PATH}" -f "${HELM_EXTRA_VALUES_PATH}" | \ | |
kubectl apply -f - --dry-run=client -o json | \ | |
jq -c '.items[] | {"kind": .kind, "name": .metadata.name, "namespace": .metadata.namespace}') | |
# TODO | |
echo "${RESOURCES_TO_ADOPT_JSON}" | while IFS= read -r line; do | |
printf "[info] Object found, processing: %s \n" "${line}" | |
KIND=$(echo $line | jq '.kind' | tr -d '"') | |
NAME=$(echo $line | jq '.name' | tr -d '"') | |
NAMESPACE=$(echo $line | jq '.namespace' | tr -d '"') | |
# Detect empty namespaces: they are commonly CRDs | |
if [ -z "${NAMESPACE}" ] || [ "${NAMESPACE}" = "null" ]; then | |
kubectl label "${KIND}" "${NAME}" app.kubernetes.io/managed-by=Helm | |
kubectl annotate "${KIND}" "${NAME}" meta.helm.sh/release-name="${RELEASE_NAME}" | |
kubectl annotate "${KIND}" "${NAME}" meta.helm.sh/release-namespace="${RELEASE_NAMESPACE}" | |
else | |
kubectl label "${KIND}" "${NAME}" --namespace="${NAMESPACE}" app.kubernetes.io/managed-by=Helm | |
kubectl annotate "${KIND}" "${NAME}" --namespace="${NAMESPACE}" meta.helm.sh/release-name="${RELEASE_NAME}" | |
kubectl annotate "${KIND}" "${NAME}" --namespace="${NAMESPACE}" meta.helm.sh/release-namespace="${RELEASE_NAMESPACE}" | |
fi | |
printf "%s\n\n" "[ok] Processed" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment