Files
italiadatacenter/add-listener.sh
alessandro 20d506407a primo
2026-07-17 09:42:52 +02:00

82 lines
2.0 KiB
Bash

#!/bin/bash
# Aggiunge un listener HTTPS direttamente sulla risorsa K8s Gateway
# main-gateway nel namespace nginx-gateway, tramite kubectl patch.
#
# Uso:
# ./add-listener.sh <hostname> <name> <secret-name>
#
# Esempio:
# ./add-listener.sh sonarqube.italiadatacenter.com https-sonarqube sonarqube-secret
set -euo pipefail
GATEWAY_NAME="main-gateway"
GATEWAY_NS="nginx-gateway"
HOSTNAME_VAL="${1:-}"
NAME_VAL="${2:-}"
SECRET_NAME="${3:-}"
if [[ -z "$HOSTNAME_VAL" || -z "$NAME_VAL" || -z "$SECRET_NAME" ]]; then
echo "Uso: $0 <hostname> <name> <secret-name>"
echo "Es.: $0 sonarqube.italiadatacenter.com https-sonarqube sonarqube-secret"
exit 1
fi
# Controlla idempotenza: verifica se il listener esiste già per nome o hostname
EXISTING=$(kubectl get gateway "$GATEWAY_NAME" -n "$GATEWAY_NS" \
-o jsonpath='{.spec.listeners[*].name}')
if echo "$EXISTING" | grep -qw "$NAME_VAL"; then
echo "Attenzione: listener con name '${NAME_VAL}' già presente. Nessuna modifica."
exit 0
fi
EXISTING_HOSTS=$(kubectl get gateway "$GATEWAY_NAME" -n "$GATEWAY_NS" \
-o jsonpath='{.spec.listeners[*].hostname}')
if echo "$EXISTING_HOSTS" | grep -qw "$HOSTNAME_VAL"; then
echo "Attenzione: listener con hostname '${HOSTNAME_VAL}' già presente. Nessuna modifica."
exit 0
fi
# JSON Patch: aggiunge il nuovo listener in append alla lista
PATCH=$(cat <<EOF
[{
"op": "add",
"path": "/spec/listeners/-",
"value": {
"allowedRoutes": {
"namespaces": {
"from": "All"
}
},
"hostname": "${HOSTNAME_VAL}",
"name": "${NAME_VAL}",
"port": 443,
"protocol": "HTTPS",
"tls": {
"certificateRefs": [
{
"group": "",
"kind": "Secret",
"name": "${SECRET_NAME}"
}
],
"mode": "Terminate"
}
}
}]
EOF
)
kubectl patch gateway "$GATEWAY_NAME" \
-n "$GATEWAY_NS" \
--type=json \
-p "$PATCH"
echo "Listener aggiunto alla risorsa ${GATEWAY_NS}/${GATEWAY_NAME}:"
echo " hostname : ${HOSTNAME_VAL}"
echo " name : ${NAME_VAL}"
echo " secret : ${SECRET_NAME}"