Kubernetes wait that apiVersion and kind exists before trying to apply resource using those

1/18/2019

How can I check and/or wait that apiVersion and kind exists before trying to apply resource using those?

Example:

Install cilium and network policy using cilium

kubectl apply -f cilium.yaml
kubectl apply -f policy.yaml # fails if run just after installing cilium, since cilium.io/v2 and CiliumNetworkPolicy doesn't exist yet

cilium.yaml

policy.yaml

apiVersion: cilium.io/v2
description: example policy
kind: CiliumNetworkPolicy
...

EDIT: (solved with following script)

#! /bin/bash

function check_api {
    local try=0
    local retries=30
    until (kubectl "api-$1s" | grep -P "\b$2\b") &>/dev/null; do
        (( ++try > retries )) && exit 1
        echo "$2 not found. Retry $try/$retries"
        sleep 3
    done
}

kubectl apply -f cilium.yaml
check_api version cilium.io/v2
check_api resource CiliumNetworkPolicy
kubectl apply -f policy.yaml
-- warbaque
kubernetes

1 Answer

1/18/2019

You can use the following to check for supported versions and kinds, that is, check what the API server you're talking to supports:

$ kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
...
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

There's also kubectl api-resources that provides you with a tabular overview of the kinds, shortnames, and if a resource is namespaced or not.

-- Michael Hausenblas
Source: StackOverflow