Search code examples
kuberneteskubectl

Use the Kubernetes REST API without kubectl


You can simply interact with K8s using its REST API. For example to get pods:

curl http://IPADDR/api/v1/pods

However I can't find any example of authentication based only on curl or REST. All the examples show the usage of kubectl as proxy or as a way to get credentials.

If I already own the .kubeconfig, and nothing else, is there any way to send the HTTP requests directly (e.g. with a token) without using kubectl?


Solution

  • The kubeconfig file you download when you first install the cluster includes a client certificate and key. For example:

    clusters:
    - cluster:
        certificate-authority-data: ...
        server: https://api.cluster1.ocp.virt:6443
      name: cluster1
    contexts:
    - context:
        cluster: cluster1
        user: admin
      name: admin
    current-context: admin
    preferences: {}
    users:
    - name: admin
      user:
        client-certificate-data: ...
        client-key-data: ...
    

    If you extract the client-certificate-data and client-key-data to files, you can use them to authenticate with curl. To extract the data:

    $ yq  -r '.users[0].user."client-certificate-data"'  kubeconfig | base64 -d > cert
    $ yq  -r '.users[0].user."client-key-data"'  kubeconfig | base64 -d >
    key
    

    And then using curl:

    $ curl -k --cert cert --key key \
      'https://api.cluster1.ocp.virt:6443/api/v1/namespaces/default/pods?limit=500'
    {
      "kind": "PodList",
      "apiVersion": "v1",
      "metadata": {
        "resourceVersion": "22022"
      },
      "items": []
    

    Alternately, if your .kubeconfig has tokens in it, like this:

    [...]
    users:
    - name: your_username/api-clustername-domain:6443
      user:
        token: sha256~...
    

    Then you can use that token as a bearer token:

    $ curl -k https://api.mycluster.mydomain:6443/ -H 'Authorization: Bearer sha256~...'
    

    ...but note that those tokens typically expire after some time, while the certificates should work indefinitely (unless they are revoked somehow).