Skip to content

Instantly share code, notes, and snippets.

@dewe
Last active May 30, 2021 07:37
Show Gist options
  • Save dewe/12c82bacac72a8a15ce44a93d218daf8 to your computer and use it in GitHub Desktop.
Save dewe/12c82bacac72a8a15ce44a93d218daf8 to your computer and use it in GitHub Desktop.
Script using jq and yq to upgrade kubernetes ingress version from networking.k8s.io/v1beta1 to networking.k8s.io/v1
#!/usr/bin/env bash
# Upgrade ingress resource api version to v1.
#
# USAGE:
# convert-ingress-version.sh [OPTIONS] <FILE>
#
# OPTIONS:
# -i update the yaml file inplace.
#
# ------------------------------------------------------------
# apiVersion: networking.k8s.io/v1beta1 -> networking.k8s.io/v1`
# spec.backend -> spec.defaultBackend
# serviceName -> service.name
# servicePort -> service.port.name (for string values)
# servicePort -> service.port.number (for numeric values)
# pathType: ImplementationSpecific (no longer has a default value in v1; "Exact", "Prefix", or "ImplementationSpecific" must be specified)
# ------------------------------------------------------------
set -euo pipefail
options=()
file=$1
if [ "$file" == "-i" ]; then
options=(--inplace)
file=$2
echo "Converting inline: $2..."
fi
if ! yq eval -e '.apiVersion == "networking.k8s.io/v1beta1"' "$file" >/dev/null 2>&1; then
echo "error: wrong apiVersion"
exit 1
fi
# spec modifications
modified_spec=$(
yq eval -j '.spec' "$file" |
jq '
def get_port:
if .servicePort|type == "number" then
{number: .servicePort}
else
{name: .servicePort}
end;
def convert_backend: {service: {name: .serviceName, port: get_port}};
with_entries(if .key == "backend"
then (.key = "defaultBackend" | .value |= convert_backend)
else .
end) |
.rules[].http.paths[] |= {
path,
pathType: (.pathType // "ImplementationSpecific"),
backend: (.backend | convert_backend)
}
'
)
export modified_spec
# root level modifications, preserving annotations and comments
yq -P "${options[@]}" eval '.apiVersion = "networking.k8s.io/v1" | .spec = env(modified_spec)' "$file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment