首页 > 其他分享 >kubernetes api访问权限控制体验之一

kubernetes api访问权限控制体验之一

时间:2023-04-28 17:11:08浏览次数:49  
标签:service kubernetes 294d system istio controller api 权限 ClusterRole

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

相关文章

  • Unity中Android API 28之后无法HTTP请求
    本文节选自洪流学堂公众号技术专栏《大话Unity2019》,未经允许不可转载。洪流学堂公众号回复log,获取最新版运行时查看日志的工具。小新:“最近我升级到AndroidAPILevel28之后,发现发布的安卓包,网络请求都不通了,这是咋回事啊?”大智:“遇到这种问题,调试的时候首先去看日志,你研究运行日......
  • Java获取1688商品详情API接口示例说明
    ​ 在使用JavaWeb类的时候,如果我们需要获取一个网站中某个商品的详细信息,我们可以使用JavaScript来获取。我们可以用JavaScript来实现一个获取商品详情的API接口,来获取一个网站中某个商品的详细信息。在使用JavaScript进行接口请求时,可以使用下面的方法:通过javascript获......
  • 淘宝店铺商品详情接口代码-获取淘宝商品详情 API 接口返回值说明示例
    ​现在某宝的规则越来越严,想要入驻某宝需要审核的特别严格,不然就会被封店,那么大家知道某宝店铺商品详情接口吗?下面是我整理的关于某宝店铺商品详情接口的相关内容,大家可以来了解下! 目前提供的接口有:商品详情、商品详情原数据、商品评论、商品快递费用、淘宝分类详情、关键字搜......
  • Kubernetes——浅聊 Affinity,就这么点东西
    浅聊Affinity,就这么点东西在Kubernetes中,Affinity是指用于控制Pod调度的策略,包括亲和性(Affinity)和反亲和性(Anti-Affinity)2种。亲和性(Affinity)包括NodeAffinity和PodAffinity2种。 一、亲和性(Affinity)表示Pod需要部署在哪些节点上。比如需要部署在某些特定的节点......
  • Kubernetes 之 Prometheus 监控 blackbox_exporter
      下载地址:https://prometheus.io/download/#blackbox_exporter#blackbox_exporter是Prometheus官方提供的一个exporter,可以监控HTTP、HTTPS,、DNS、TCP、ICMP等目标实例,#从而实现对被监控节点进行监控和数据采集。#HTTP/HTPPS:URL/API可用性检测#TCP:端口监......
  • Fastapi之微服务Consul应用注册发现
    importuvicornfromfastapiimportFastAPIapp=FastAPI()defregister(server_name,ip,port):c=consul.Consul(host="127.0.0.1",port=8500)#consul服务器信息print(f"开始注册服务{server_name}")check=consul.Check.tcp(ip,po......
  • Fastapi之OAuth2认证
    1.基于用户名密码认证fromtypingimportOptionalfromfastapiimportAPIRouter,Depends,HTTPExceptionfromfastapi.securityimportOAuth2PasswordBearer,OAuth2PasswordRequestFormfrompydanticimportBaseModelfromstarletteimportstatustokens=APIRout......
  • 基于台风信息查询 API 设计台风预警系统的基本思路
    引言在过去的几十年中,由于全球气候变化等因素的影响,台风的强度和频率都有所增加,给人类社会带来了极大的威胁。在这种背景下,一个高效可靠的台风预警和监测系统显得尤为重要。这种系统可以通过获取、存储、处理和分析各种相关数据,来实现对台风的实时监测、预测和预警,并向相关部门和......
  • API 架构风格演化史:CORBA-XMLRPC(SOAP)-REST-JSONRPC-GraphQL-gRPC
    我们先来看一张 TwitterArchitecture2022CodeFirstv.sAPIFirst软件开发理念的改变下图显示了代码优先开发和API优先开发之间的差异。为什么我们要考虑API优先设计?微服务增加了系统的复杂性。我们有单独的服务来服务系统的不同功能。尽管这种体系结构促进了职责的脱钩和分......
  • 基于机器学习的纠错系统技术 - 智能文本纠错 API
    引言在过去的几十年里,文本纠错技术已经取得了巨大的进展,从最初的基于规则的纠错系统到现在的基于机器学习的纠错系统,技术的发展已经帮助人们解决了大量的文本纠错问题,随着机器学习技术的发展,文本纠错技术也发生了重大变化。本文将介绍一款新的基于机器学习的纠错技术,并详细列出......