diff --git a/scripts/dev/infra-sync.sh b/scripts/dev/infra-sync.sh index 0fa38f6..a069c67 100755 --- a/scripts/dev/infra-sync.sh +++ b/scripts/dev/infra-sync.sh @@ -94,7 +94,7 @@ kubecfg_merge() { echo "Merging kube configurations into ${infra_kubeconfig}" tmp_infra_kubeconfig=$(mktemp) - kubectl config view --flatten > "${tmp_infra_kubeconfig}" + kubectl config view --flatten -o json | jq -f rename-kubeconfig-ctx.jq > "${tmp_infra_kubeconfig}" mv "${tmp_infra_kubeconfig}" "${infra_kubeconfig}" } diff --git a/scripts/dev/rename-kubeconfig-ctx.jq b/scripts/dev/rename-kubeconfig-ctx.jq new file mode 100755 index 0000000..e3a8423 --- /dev/null +++ b/scripts/dev/rename-kubeconfig-ctx.jq @@ -0,0 +1,72 @@ +#!/usr/bin/env -S jq -f +# +# Pass JSON kubeconfig to this jq script to rename +# the contexts to the referenced cluster names, +# and the cluster names to the referenced user names. +# This should help to merge kubeconfigs with non-unique +# contexts and user names. +# +. as $cfg +| ( + # Build context_map as an array of objects with name transformations. + $cfg.contexts + | map({ + old_name: .name, + cluster: .context.cluster, + old_user: .context.user, + new_name: .context.cluster, + new_user: (.context as $ctx + | .context.user + | (if endswith($ctx.cluster) + then . else (. + "@" + $ctx.cluster) end) + ) + }) +) as $context_map +# Reconstruct the config from scratch. +| { + kind: $cfg.kind, + apiVersion: $cfg.apiVersion, + preferences: $cfg.preferences, + clusters: $cfg.clusters, + contexts: ( + $context_map + | map({ + name: .new_name, + context: { + cluster: .cluster, + user: .new_user + } + }) + ), + users: ( + $cfg.users + | map( + . as $user + | ( + $context_map + | map(select(.old_user == $user.name)) + | if length > 0 then + { + name: .[0].new_user, + user: $user.user + } + else + $user + end + ) + ) + ), +} +# Conditionally include current-context if it existed originally. +| if $cfg | has("current-context") then + . + { + "current-context": ( + $cfg["current-context"] as $curr + | $context_map + | map(select(.old_name == $curr)) + | if length > 0 then .[0].new_name else $curr end + ) + } +else . +end +