Skip to content

Instantly share code, notes, and snippets.

@va3093
Created February 4, 2021 12:20
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 va3093/3f97681fd42cb7bc8fc57b0a0d87d259 to your computer and use it in GitHub Desktop.
Save va3093/3f97681fd42cb7bc8fc57b0a0d87d259 to your computer and use it in GitHub Desktop.
Access k8s example

Access K8s example

I played around with a few approaches and this seems to be the simplest. You can use this to experiment with the api.

This sets up an ubuntu box with curl pre-installed. It also creates a service account with permissions to see pods and jobs. The auth token created by this service account is stored at /var/run/secrets/kubernetes.io/serviceaccount/token

apiVersion: v1
kind: ServiceAccount
metadata:
  name: access-k8s-api

---

apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
  name: access-k8s-api
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get","watch","list"]
- apiGroups: ["batch"]
  resources: ["jobs"]
  verbs: ["get", "delete", "list", "create", "update"]

---

apiVersion: rbac.authorization.k8s.io/v1beta1
kind: RoleBinding
metadata:
  name: access-k8s-api
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: access-k8s-api
subjects:
- kind: ServiceAccount
  name: access-k8s-api
  namespace: default

---

apiVersion: v1
kind: Pod
metadata:
  name: ubuntu
spec:
  serviceAccountName: access-k8s-api
  containers:
  - name: ubuntu
    image: tutum/curl
    command: ["/bin/bash"]
    args: ['-c','sleep 60000']
    ports:
    - containerPort: 80

If you apply this you can exec into the ubuntu box.

kubectl exec -it ubuntu -- /bin/sh

Once you are in you can hit the api

# Set token
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

# Hit api (Get pods)
curl -sSk -H "Authorization: Bearer $TOKEN"  https://$KUBERNETES_SERVICE_HOST:$KUBERNETES_PORT_443_TCP_PORT/api/v1/namespaces/default/pods/$HOSTNAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment