1.简介
目前想实现通过python脚本,实时获取k8s的service信息,然后写成nginx.conf脚本,并且也让chatgpt写了代码。
运行的时候提示401权限不够:
root@gateway-7576bf68bb-cf55t:/usr/local/openresty# python3 gen_nginx_conf.py
Traceback (most recent call last):
File "gen_nginx_conf.py", line 25, in <module>
services = v1.list_service_for_all_namespaces().items
File "/usr/local/lib/python3.6/dist-packages/kubernetes/client/api/core_v1_api.py", line 18239, in list_service_for_all_namespaces
return self.list_service_for_all_namespaces_with_http_info(**kwargs) # noqa: E501
File "/usr/local/lib/python3.6/dist-packages/kubernetes/client/api/core_v1_api.py", line 18360, in list_service_for_all_namespaces_with_http_info
collection_formats=collection_formats)
File "/usr/local/lib/python3.6/dist-packages/kubernetes/client/api_client.py", line 353, in call_api
_preload_content, _request_timeout, _host)
File "/usr/local/lib/python3.6/dist-packages/kubernetes/client/api_client.py", line 184, in __call_api
_request_timeout=_request_timeout)
File "/usr/local/lib/python3.6/dist-packages/kubernetes/client/api_client.py", line 377, in request
headers=headers)
File "/usr/local/lib/python3.6/dist-packages/kubernetes/client/rest.py", line 245, in GET
query_params=query_params)
File "/usr/local/lib/python3.6/dist-packages/kubernetes/client/rest.py", line 235, in request
raise ApiException(http_resp=r)
kubernetes.client.exceptions.ApiException: (403)
Reason: Forbidden
HTTP response headers: HTTPHeaderDict({'Audit-Id': '8abe80ad-642b-479d-99b5-cb06f02ed0cd', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff', 'X-Kubernetes-Pf-Flowschema-Uid': 'c44586f0-736b-4e89-aba4-25ef1c1d56a8', 'X-Kubernetes-Pf-Prioritylevel-Uid': 'e837ccde-933a-4026-ac8e-f4dd4838a2a8', 'Date': 'Fri, 28 Apr 2023 07:55:55 GMT', 'Content-Length': '286'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"services is forbidden: User \"system:serviceaccount:default:default\" cannot list resource \"services\" in API group \"\" at the cluster scope","reason":"Forbidden","details":{"kind":"services"},"code":403}
继续问chatgpt,它说需要创建serviceaccount账号,绑定角色clusterrolebinding:
1.创建一个具有足够权限的服务账户
您可以使用以下命令创建一个具有足够权限的服务账户,并为其授予访问"services"资源的权限:
$ kubectl create serviceaccount my-service-account
$ kubectl create clusterrolebinding my-service-account --clusterrole=view --serviceaccount=default:my-service-account
这将创建一个名为"my-service-account"的服务账户,并将其绑定到"view"集群角色,该角色允许访问"services"资源。
2. 在容器中使用服务账户
您可以在容器中使用以下代码来加载服务账户的配置,并使用该账户访问Kubernetes API:
from kubernetes import client, config
# 加载my-service-account的配置
config.load_incluster_config()
configuration = client.Configuration()
configuration.assert_hostname = False
configuration.ssl_ca_cert = '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'
configuration.api_key = {'authorization': 'Bearer ' + open('/var/run/secrets/kubernetes.io/serviceaccount/token').read()}
configuration.host = 'https://' + os.environ['KUBERNETES_SERVICE_HOST'] + ':' + os.environ['KUBERNETES_SERVICE_PORT']
# 创建Kubernetes API客户端
v1 = client.CoreV1Api(api_client=client.ApiClient(configuration))
# 获取所有Namespace中的Service信息
services = v1.list_service_for_all_namespaces().items
# 打印每个Service的名称和IP地址
for service in services:
print("Name: %s, IP: %s" % (service.metadata.name, service.spec.cluster_ip))
然后就研究了下serviceaccount
2.serviceaccount相关了解
官网:
https://kubernetes.io/zh-cn/docs/tasks/configure-pod-container/configure-service-account/
使用默认的服务账号访问 API 服务器
当 Pod 与 API 服务器联系时,Pod 会被认证为某个特定的 ServiceAccount(例如:default)。 在每个名字空间中,至少存在一个 ServiceAccount。
每个 Kubernetes 名字空间至少包含一个 ServiceAccount:也就是该名字空间的默认服务账号, 名为 default。如果你在创建 Pod 时没有指定 ServiceAccount,Kubernetes 会自动将该名字空间中 名为 default 的 ServiceAccount 分配给该 Pod。
你可以检视你刚刚创建的 Pod 的细节。例如:
kubectl get pods/<podname> -o yaml
在输出中,你可以看到字段 spec.serviceAccountName。当你在创建 Pod 时未设置该字段时, Kubernetes 自动为 Pod 设置这一属性的取值。
Pod 中运行的应用可以使用这一自动挂载的服务账号凭据来访问 Kubernetes API。 参阅访问集群以进一步了解。
当 Pod 被身份认证为某个 ServiceAccount 时, 其访问能力取决于所使用的鉴权插件和策略。
文章中pod会默认挂载一个default的serviceaccount,来看一下:
qiteck@server:~$ sudo kubectl get serviceaccount
NAME SECRETS AGE
default 0 294d
service-viewer 0 44m
qiteck@server:~$ sudo kubectl describe serviceaccount default
Name: default
Namespace: default
Labels: <none>
Annotations: <none>
Image pull secrets: <none>
Mountable secrets: <none>
Tokens: <none>
Events: <none>
确实有default的账号,我们来看一下clusterrolebinding:
qiteck@server:~$ sudo kubectl get clusterrolebinding
NAME ROLE AGE
cluster-admin ClusterRole/cluster-admin 294d
flannel ClusterRole/flannel 293d
ingress-nginx ClusterRole/ingress-nginx 38d
ingress-nginx-admission ClusterRole/ingress-nginx-admission 38d
istio-reader-clusterrole-istio-system ClusterRole/istio-reader-clusterrole-istio-system 8d
istio-reader-istio-system ClusterRole/istio-reader-istio-system 8d
istiod-clusterrole-istio-system ClusterRole/istiod-clusterrole-istio-system 8d
istiod-gateway-controller-istio-system ClusterRole/istiod-gateway-controller-istio-system 8d
istiod-istio-system ClusterRole/istiod-istio-system 8d
kiali ClusterRole/kiali 5d6h
kubeadm:get-nodes ClusterRole/kubeadm:get-nodes 294d
kubeadm:kubelet-bootstrap ClusterRole/system:node-bootstrapper 294d
kubeadm:node-autoapprove-bootstrap ClusterRole/system:certificates.k8s.io:certificatesigningrequests:nodeclient 294d
kubeadm:node-autoapprove-certificate-rotation ClusterRole/system:certificates.k8s.io:certificatesigningrequests:selfnodeclient 294d
kubeadm:node-proxier ClusterRole/system:node-proxier 294d
metrics-server:system:auth-delegator ClusterRole/system:auth-delegator 78d
prometheus ClusterRole/prometheus 5d6h
system:basic-user ClusterRole/system:basic-user 294d
system:controller:attachdetach-controller ClusterRole/system:controller:attachdetach-controller 294d
system:controller:certificate-controller ClusterRole/system:controller:certificate-controller 294d
system:controller:clusterrole-aggregation-controller ClusterRole/system:controller:clusterrole-aggregation-controller 294d
system:controller:cronjob-controller ClusterRole/system:controller:cronjob-controller 294d
system:controller:daemon-set-controller ClusterRole/system:controller:daemon-set-controller 294d
system:controller:deployment-controller ClusterRole/system:controller:deployment-controller 294d
system:controller:disruption-controller ClusterRole/system:controller:disruption-controller 294d
system:controller:endpoint-controller ClusterRole/system:controller:endpoint-controller 294d
system:controller:endpointslice-controller ClusterRole/system:controller:endpointslice-controller 294d
system:controller:endpointslicemirroring-controller ClusterRole/system:controller:endpointslicemirroring-controller 294d
system:controller:ephemeral-volume-controller ClusterRole/system:controller:ephemeral-volume-controller 294d
system:controller:expand-controller ClusterRole/system:controller:expand-controller 294d
system:controller:generic-garbage-collector ClusterRole/system:controller:generic-garbage-collector 294d
system:controller:horizontal-pod-autoscaler ClusterRole/system:controller:horizontal-pod-autoscaler 294d
system:controller:job-controller ClusterRole/system:controller:job-controller 294d
system:controller:namespace-controller ClusterRole/system:controller:namespace-controller 294d
system:controller:node-controller ClusterRole/system:controller:node-controller 294d
system:controller:persistent-volume-binder ClusterRole/system:controller:persistent-volume-binder 294d
system:controller:pod-garbage-collector ClusterRole/system:controller:pod-garbage-collector 294d
system:controller:pv-protection-controller ClusterRole/system:controller:pv-protection-controller 294d
system:controller:pvc-protection-controller ClusterRole/system:controller:pvc-protection-controller 294d
system:controller:replicaset-controller ClusterRole/system:controller:replicaset-controller 294d
system:controller:replication-controller ClusterRole/system:controller:replication-controller 294d
system:controller:resourcequota-controller ClusterRole/system:controller:resourcequota-controller 294d
system:controller:root-ca-cert-publisher ClusterRole/system:controller:root-ca-cert-publisher 294d
system:controller:route-controller ClusterRole/system:controller:route-controller 294d
system:controller:service-account-controller ClusterRole/system:controller:service-account-controller 294d
system:controller:service-controller ClusterRole/system:controller:service-controller 294d
system:controller:statefulset-controller ClusterRole/system:controller:statefulset-controller 294d
system:controller:ttl-after-finished-controller ClusterRole/system:controller:ttl-after-finished-controller 294d
system:controller:ttl-controller ClusterRole/system:controller:ttl-controller 294d
system:coredns ClusterRole/system:coredns 294d
system:discovery ClusterRole/system:discovery 294d
system:kube-controller-manager ClusterRole/system:kube-controller-manager 294d
system:kube-dns ClusterRole/system:kube-dns 294d
system:kube-scheduler ClusterRole/system:kube-scheduler 294d
system:metrics-server ClusterRole/system:metrics-server 78d
system:monitoring ClusterRole/system:monitoring 294d
system:node ClusterRole/system:node 294d
system:node-proxier ClusterRole/system:node-proxier 294d
system:public-info-viewer ClusterRole/system:public-info-viewer 294d
system:service-account-issuer-discovery ClusterRole/system:service-account-issuer-discovery 294d
system:volume-scheduler ClusterRole/system:volume-scheduler 294d
可以发现没有ClusterRole/view的role,所以我想手动给它加一个:
qiteck@server:~$ kubectl create clusterrolebinding default-crb --clusterrole=view --serviceaccount=default:default
clusterrolebinding.rbac.authorization.k8s.io/default-crb created
给default这个账号,创建一个view的角色,可以查看default这个命名空间的service。
再看一下clusterrolebinding:
qiteck@server:~$ sudo kubectl get clusterrolebinding
NAME ROLE AGE
cluster-admin ClusterRole/cluster-admin 294d
default-crb ClusterRole/view 27s
flannel ClusterRole/flannel 293d
ingress-nginx ClusterRole/ingress-nginx 38d
ingress-nginx-admission ClusterRole/ingress-nginx-admission 38d
istio-reader-clusterrole-istio-system ClusterRole/istio-reader-clusterrole-istio-system 8d
istio-reader-istio-system ClusterRole/istio-reader-istio-system 8d
istiod-clusterrole-istio-system ClusterRole/istiod-clusterrole-istio-system 8d
istiod-gateway-controller-istio-system ClusterRole/istiod-gateway-controller-istio-system 8d
istiod-istio-system ClusterRole/istiod-istio-system 8d
kiali ClusterRole/kiali 5d6h
kubeadm:get-nodes ClusterRole/kubeadm:get-nodes 294d
kubeadm:kubelet-bootstrap ClusterRole/system:node-bootstrapper 294d
kubeadm:node-autoapprove-bootstrap ClusterRole/system:certificates.k8s.io:certificatesigningrequests:nodeclient 294d
kubeadm:node-autoapprove-certificate-rotation ClusterRole/system:certificates.k8s.io:certificatesigningrequests:selfnodeclient 294d
kubeadm:node-proxier ClusterRole/system:node-proxier 294d
metrics-server:system:auth-delegator ClusterRole/system:auth-delegator 78d
prometheus ClusterRole/prometheus 5d6h
system:basic-user ClusterRole/system:basic-user 294d
system:controller:attachdetach-controller ClusterRole/system:controller:attachdetach-controller 294d
system:controller:certificate-controller ClusterRole/system:controller:certificate-controller 294d
system:controller:clusterrole-aggregation-controller ClusterRole/system:controller:clusterrole-aggregation-controller 294d
system:controller:cronjob-controller ClusterRole/system:controller:cronjob-controller 294d
system:controller:daemon-set-controller ClusterRole/system:controller:daemon-set-controller 294d
system:controller:deployment-controller ClusterRole/system:controller:deployment-controller 294d
system:controller:disruption-controller ClusterRole/system:controller:disruption-controller 294d
system:controller:endpoint-controller ClusterRole/system:controller:endpoint-controller 294d
system:controller:endpointslice-controller ClusterRole/system:controller:endpointslice-controller 294d
system:controller:endpointslicemirroring-controller ClusterRole/system:controller:endpointslicemirroring-controller 294d
system:controller:ephemeral-volume-controller ClusterRole/system:controller:ephemeral-volume-controller 294d
system:controller:expand-controller ClusterRole/system:controller:expand-controller 294d
system:controller:generic-garbage-collector ClusterRole/system:controller:generic-garbage-collector 294d
system:controller:horizontal-pod-autoscaler ClusterRole/system:controller:horizontal-pod-autoscaler 294d
system:controller:job-controller ClusterRole/system:controller:job-controller 294d
system:controller:namespace-controller ClusterRole/system:controller:namespace-controller 294d
system:controller:node-controller ClusterRole/system:controller:node-controller 294d
system:controller:persistent-volume-binder ClusterRole/system:controller:persistent-volume-binder 294d
system:controller:pod-garbage-collector ClusterRole/system:controller:pod-garbage-collector 294d
system:controller:pv-protection-controller ClusterRole/system:controller:pv-protection-controller 294d
system:controller:pvc-protection-controller ClusterRole/system:controller:pvc-protection-controller 294d
system:controller:replicaset-controller ClusterRole/system:controller:replicaset-controller 294d
system:controller:replication-controller ClusterRole/system:controller:replication-controller 294d
system:controller:resourcequota-controller ClusterRole/system:controller:resourcequota-controller 294d
system:controller:root-ca-cert-publisher ClusterRole/system:controller:root-ca-cert-publisher 294d
system:controller:route-controller ClusterRole/system:controller:route-controller 294d
system:controller:service-account-controller ClusterRole/system:controller:service-account-controller 294d
system:controller:service-controller ClusterRole/system:controller:service-controller 294d
system:controller:statefulset-controller ClusterRole/system:controller:statefulset-controller 294d
system:controller:ttl-after-finished-controller ClusterRole/system:controller:ttl-after-finished-controller 294d
system:controller:ttl-controller ClusterRole/system:controller:ttl-controller 294d
system:coredns ClusterRole/system:coredns 294d
system:discovery ClusterRole/system:discovery 294d
system:kube-controller-manager ClusterRole/system:kube-controller-manager 294d
system:kube-dns ClusterRole/system:kube-dns 294d
system:kube-scheduler ClusterRole/system:kube-scheduler 294d
system:metrics-server ClusterRole/system:metrics-server 78d
system:monitoring ClusterRole/system:monitoring 294d
system:node ClusterRole/system:node 294d
system:node-proxier ClusterRole/system:node-proxier 294d
system:public-info-viewer ClusterRole/system:public-info-viewer 294d
system:service-account-issuer-discovery ClusterRole/system:service-account-issuer-discovery 294d
system:volume-scheduler ClusterRole/system:volume-scheduler 294d
这样应该default这个账号就有了view service的能力了,我们来试试:
再试一下,脚本就能正常运行了。
标签:service,kubernetes,294d,system,istio,controller,api,权限,ClusterRole From: https://www.cnblogs.com/zhanchenjin/p/17362643.html