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 .


译文:

在namepace project-hamster 中有一个现有的ServiceAccount secret-reader 。创建一个名为 tmp-api-contact 的pod, 镜像为 curl:7.65.3 ,使用这个ServiceAccount。确保该容器持续运行。

在pod中,使用curl手动访问该集群的Kubernetes Api,列出所有可用的secret。你可以忽略不安全的HTTPS连接。把这个命令写进文件 /opt/course/e4/list-secrets.sh


解答:

参考: https://kubernetes.io/docs/tasks/run-application/access-api-from-pod

kubectl config use-context k8s-c1-H

创建pod

k run tmp-api-contact \
  --image=curlimages/curl:7.65.3 $do \
  --command -- sh -c 'sleep 1d' > e2.yaml

vim e2.yaml

e2.yaml

# e2.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: tmp-api-contact
  name: tmp-api-contact
  namespace: project-hamster          # add
spec:
  serviceAccountName: secret-reader   # add
  containers:
  - command:
    - sh
    - -c
    - sleep 1d
    image: curlimages/curl:7.65.3
    name: tmp-api-contact
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}

运行pod

k -f e2.yaml create

检查是否可以获取secret

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

进入pod,可以通过如下命令访问, -k参数是忽略证书认证

k -n project-hamster exec tmp-api-contact -it -- sh
~ curl https://kubernetes.default
~ curl -k https://kubernetes.default
~ curl -k https://kubernetes.default/api/v1/secrets

使用带验证头的方式进行访问

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

可以使用ca证书进行访问,不用-k参数

CACERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
curl --cacert ${CACERT} https://kubernetes.default/api/v1/secrets -H "Authorization: Bearer ${TOKEN}"

上面的命令可以写入文件 /opt/course/e4/list-secrets.sh

# /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}"

Killer.sh CKA模拟题目 汇总