Skip to content

Instantly share code, notes, and snippets.

@danrspencer
Created May 4, 2021 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danrspencer/f695a22b15b1e4e3b3cae75a7a8a93ec to your computer and use it in GitHub Desktop.
Save danrspencer/f695a22b15b1e4e3b3cae75a7a8a93ec to your computer and use it in GitHub Desktop.
Extract and fully expand a Kubernetes definition
#!/bin/bash
trap "kill 0" EXIT
# Setup the proxy and wait for it to connect
kubectl proxy &
timeout 10s bash -c "until curl http://127.0.0.1:8001/; do sleep 1; done"
# Grab the Kubernetes openapi schema from the API
SCHEMA=$(curl http://127.0.0.1:8001/openapi/v2)
# Get the schema
SPEC=$(echo "${SCHEMA}" | jq '.definitions."io.k8s.api.apps.v1.StatefulSetSpec"')
# Recursively iterate over the schema and replace all $ref entries
# with their real schema
DEPTH=0
until [[ ${DEPTH} -gt 1 && -z ${REFS} ]]
do
REFS=$(echo "${SPEC}" | jq --raw-output '.. | objects | ."$ref" //empty')
for REF in ${REFS}
do
echo ${DEPTH}: ${REF}
REF_KEY=${REF##"#/definitions/"}
REF_OBJECT=$(echo "${SCHEMA}" | jq ".definitions.\"${REF_KEY}\"")
SPEC=$(echo "${SPEC}" | jq "(.. | objects | select( .\"\$ref\" == \"${REF}\")) |= ${REF_OBJECT}")
done
((DEPTH++))
done
# Delete unwanted / unsupported keys and convert to YAML
echo "${SPEC}" \
| jq 'del(.. | ."x-kubernetes-patch-merge-key"?, ."x-kubernetes-patch-strategy"?, ."x-kubernetes-group-version-kind"?)' \
| yq r --prettyPrint - > "spec.yaml"
@the-voidl
Copy link

Thanks for this nice script.

I had to write in the last line.
| yq . -y > "spec.yaml"

Also, to let it run insinde a running pod in a cluster you can rep0lace line 10 with following code and delete lines 6-7:

APISERVER=https://kubernetes.default.svc
SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
TOKEN=$(cat ${SERVICEACCOUNT}/token)
CACERT=${SERVICEACCOUNT}/ca.crt
SCHEMA=`curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET ${APISERVER}/openapi/v2`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment