티스토리 뷰

kubernetes service account를 사용하여 cURL로 kubernetes에 접근하는 방법을 알아보자.

아래와 같은 yaml을 통해 SA(service account) role, rolebinding 그리고 secret을 생성한다.

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: default
  name: onlypods
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "watch", "list"]
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: curltest
  namespace: default
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: onlyreadpods
  namespace: default
subjects:
- kind: ServiceAccount
  name:  curltest
roleRef:
  kind: Role
  name: onlypods
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: Secret
type: kubernetes.io/service-account-token
metadata:
  name: curltest-secret
  annotations:
    kubernetes.io/service-account.name: curltest

참고로 1.24 이후부터 service account를 생성하더라도 secret을 자동으로 만들지 않기에 직접 생성을 해주어야 한다.

이후 kubectl 명령 수행이 가능한 환경이라면 가능하다면 아래와 같은 TOKEN과 ca.crt를 가져와 cURL을 통핸 pod 정보를 가져올수 있다.

#!/bin/bash

APISERVER=$(kubectl config view -o jsonpath='{.clusters[].cluster.server}')

TOKEN=$(kubectl get secret curltest-secret -o jsonpath='{.data.token}' | base64 -d)

kubectl get secret curltest-secret -o jsonpath='{.data.ca\.crt}' | base64 -d > test-ca.crt

curl -H "Authorization: Bearer $TOKEN" --cacert kube-ca.crt "$APISERVER/api/v1/namespaces/default/pods"

실제 아래와 같은 결과가 출력된다.

{
  "kind": "PodList",
  "apiVersion": "v1",
  "metadata": {
  ...

Reference

https://stackoverflow.com/questions/55415867/curl-kubernetes-with-serivceaccount-token-it-always-returns-unauthorized

'Cloud > Cloud Native' 카테고리의 다른 글

Falco  (0) 2021.01.03
Rook  (0) 2020.12.14
Hashicorp Waypoint  (0) 2020.10.27
How to use Hashicorp Waypoint  (0) 2020.10.27
Metallb on Minikube  (0) 2020.10.27
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함