凡ジニアのtxt

エンジニアリングができない凡ジニア

外部からcurlを用いてk8sリソースにアクセスする

はじめに

外部からKuberernetes(以下、k8s)のリソースにアクセスしたいことがあったりします。特にcurlを用いたリクエストの送信やgo/pythonなどを使った自動化など。今回はcurlを使ったリクエストの送信方法をまとめています。

実装

必要となるk8sリソース

k8sリソースを外部からリクエストを送る場合、以下のリソースを設定する必要があります。

  • service account
  • secret
  • clusterrole
  • clusterrolebinding

以下、上記のk8sリソースの関係図になります。 f:id:aki5151:20210819205823j:plain

service accountとsecretの作成

最初に、system userのようにPodなどに任意の処理させる用のアカウントとしてservice accountを作成します。またservice accountを作成した場合、secretは自動的に作成されます。

# service accountのyamlを作成
$ kubectl create sa test-sa --dry-run=client -o yaml > test-sa.yaml
$ cat test-sa.yaml

apiVersion: v1
kind: ServiceAccount
metadata:
  creationTimestamp: null
  name: test-sa

# test-saを作成
$ kubectl apply -f test-sa.yaml
serviceaccount/test-sa created

# test-saを確認
$ kubectl get sa
NAME        SECRETS   AGE
default     1         1d
test-sa     1         23s

# test-saのsecretを確認
$ kubectl get secret
NAME                    TYPE                                  DATA   AGE
default-token-nm8bq     kubernetes.io/service-account-token   3      1d
test-sa-token-jrmqf     kubernetes.io/service-account-token   3      58s

clusterroleの作成

デフォルトで作成されているclusterroleのadminを使用するので、任意のclusterroleは作成しません。

clusterrolebindingの作成

先ほど作成したservice accontとclusterroleを紐づけるために、clusterrolebindingを作成します。

# clusterrolebindingのyamlを作成
$ kubectl  create clusterrolebinding test-clusterrolebindng --clusterrole=test-clusterrole --dry-run=client --serviceaccount=default:test-sa -o yaml > test-clusterrolebindng.yaml

$ cat test-clusterrolebindng.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  creationTimestamp: null
  name: test-clusterrolebindng
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin
subjects:
- kind: ServiceAccount
  name: test-sa
  namespace: default

#  test-clusterrolebindngを作成
$ kubectl apply -f test-clusterrolebindng.yaml
clusterrolebinding.rbac.authorization.k8s.io/test-clusterrolebindng created

#  test-clusterrolebindngを確認
$ kubectl get clusterrolebinding test-clusterrolebindng
NAME                     AGE
test-clusterrolebindng   53s

外部からcurlのリクエストを送信

外部からcurlを用いて、httpsリクエストを送信できるk8sリソースの準備ができました。リクエストを送信するのには、service accountのsecretにあるTOKENが必要になります。以下のように環境変数を定義してからリクエストを送信します。

$export TOKEN=`(kubectl get secret test-sa-token-jrmqf -o json | jq -r .data.token |  base64 -d)`

$ curl -g -H "Content-Type:application/json" --header "Authorization: Bearer $TOKEN" --insecure "https://$apiserver_ip:$apiserver_port/api/v1/namespaces/default/configmaps"
{
  "kind": "ConfigMapList",
  "apiVersion": "v1",
  "metadata": {
    "selfLink": "/api/v1/namespaces/default/configmaps",
    "resourceVersion": "35090648"
  },
  "items": []
}

これでk8sから、レスポンスが返ってきたことがわかります。

所感

本記事で扱ったk8sリソースの理解不足があったりしたので、まとめてみました。意外と勉強になったなと思います。