Skip to main content

Question 27 - Manual API Access via Curl

Question 27 | Curl Manually Contact API

Use context: kubectl config use-context k8s-c1-H

There is an existing ServiceAccount secret-reader in Namespace project-hamster. Create a Pod of image curlimages/curl:7.65.3 named tmp-api-contact which uses this ServiceAccount. Make sure the container keeps running.

Exec into the Pod and use curl to access the Kubernetes Api of that cluster manually, listing all available secrets. You can ignore insecure https connection. Write the command(s) for this into file /opt/course/e4/list-secrets.sh.


kubectl config use-context k8s-c1-H

k run tmp-api-contact -n project-hamster --image curlimages/curl:7.65.3 --dry-run=client -o yaml --command sleep 5d > /opt/course/27/pod.yaml

vim pod.yaml
#/opt/course/27/pod.yaml
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: null
labels:
run: tmp-api-contact
name: tmp-api-contact
namespace: project-hamster
spec:
serviceAccountName: secret-reader
containers:
- image: curlimages/curl:7.65.3
name: tmp-api-contact
args:
- sleep
- 5d
resources: {}
dnsPolicy: ClusterFirst
restartPolicy: Always
status: {}

Let's apply...

k apply -f /opt/course/27/pod.yaml

# Let's check if the service account actually has permission for this

k auth can-i get secret --as system:serviceaccount:project-hamster:secret-reader
yes

If this pod needs to hit the api, it needs to authenticate using a token that is automatically mounted in a secret. We can use this token to access the api.

CACERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)

curl --cacert ${CACERT} https://kubernetes.default/api/v1/secrets -H "Authorization: Bearer ${TOKEN}"


# /opt/course/e4/list-secrets.sh
TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
curl -k https://kubernetes.default/api/v1/secrets -H "Authorization: Bearer ${TOKEN}"