Skip to content

Instantly share code, notes, and snippets.

@dougbtv
Last active December 4, 2020 15:30
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 dougbtv/f44207694fdddcf5e88a7376837fdeaa to your computer and use it in GitHub Desktop.
Save dougbtv/f44207694fdddcf5e88a7376837fdeaa to your computer and use it in GitHub Desktop.
Getting a container ID from the kube API with bash

First create the resources.yml to create a service account, RBAC & bindings for it, as well as a pod that uses the downward API to get its own name...

kubectl create -f resources.yml

Now you can exec into the pod...

$ kubectl exec -it toolpod -- /bin/bash

Go ahead and get your secret token, and then query the api with it:

$ KUBE_TOKEN=$(</var/run/secrets/kubernetes.io/serviceaccount/token)
$ curl -sSk -H "Authorization: Bearer $KUBE_TOKEN" https://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods/$POD_NAME | grep -i containerid
        "containerID": "docker://e9914b331ef809b5f6e27b8fc57fb6477e436edee089c9df3eabb66ec422d062",

Note: You might need to also get the namespace in the downward API, and the RBAC is very very very permissive.

If the kubernetes.default.svc.cluster.local URL isn't working for you, you might need to generate the API server URL otherwise -- do this from wherever you run kubectl and then use it in the container:

[centos@kube-singlehost-master ~]$ APISERVER=https://$(kubectl -n default get endpoints kubernetes --no-headers | awk '{ print $2 }')
[centos@kube-singlehost-master ~]$ echo $APISERVER
https://192.168.122.144:6443
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: toolboxer
rules:
- apiGroups: [""]
resources: ["*"]
verbs: ["*"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: toolboxer
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: toolboxer
subjects:
- kind: ServiceAccount
name: toolboxer
namespace: default
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: toolboxer
namespace: default
---
apiVersion: v1
kind: Pod
metadata:
name: toolpod
spec:
serviceAccountName: toolboxer
containers:
- name: toolpod
command: ["/bin/bash", "-c", "trap : TERM INT; sleep infinity & wait"]
image: centos/tools
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment