kubernetes测试环境有多个项目空间如何创建一个serviceaccount可以访问所有项目?

ミ那些﹏ 发表于: 2021-11-16   最后更新时间: 2021-11-16 17:20:23   91 游览


发表于 2021-11-16

创建serviceaccount

apiVersion: v1
kind: ServiceAccount
metadata:
  name: sa-all
  namespace: test-namespace

创建一个是集群角色(设置访问权限)

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: cluster-role-all
rules:
- apiGroups:
  - '*'
  resources:
  - '*'
  verbs:
  - '*'
- nonResourceURLs:
  - '*'
  verbs:
  - '*'

*代表所有。

verbs包括 ["get", "list", "watch", "create", "update", "patch", "delete"]权限。

你也可以设置部份权限和资源,如下

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: monitoring-endpoints
  labels:
    rbac.example.com/aggregate-to-monitoring: "true"
# 当你创建 "monitoring-endpoints" ClusterRole 时,
# 下面的规则会被添加到 "monitoring" ClusterRole 中
rules:
- apiGroups: [""]
  resources: ["services", "endpoints", "pods"]
  verbs: ["get", "list", "watch"]

通过kubectl api-resources命令可以查看kubernetes当前版本apiGroups和resources。

NAME                              SHORTNAMES       APIGROUP                       NAMESPACED   KIND
bindings                                                                          true         Binding
componentstatuses                 cs                                              false        ComponentStatus
configmaps                        cm                                              true         ConfigMap
endpoints                         ep                                              true         Endpoints
events                            ev                                              true         Event
limitranges                       limits                                          true         LimitRange
namespaces                        ns                                              false        Namespace
nodes                             no                                              false        Node
persistentvolumeclaims            pvc                                             true         PersistentVolumeClaim
persistentvolumes                 pv                                              false        PersistentVolume
pods                              po                                              true         Pod
podtemplates                                                                      true         PodTemplate
replicationcontrollers            rc                                              true         ReplicationController
resourcequotas                    quota                                           true         ResourceQuota
secrets                                                                           true         Secret
serviceaccounts                   sa                                              true         ServiceAccount
services                          svc                                             true         Service
mutatingwebhookconfigurations                      admissionregistration.k8s.io   false        MutatingWebhookConfiguration
validatingwebhookconfigurations                    admissionregistration.k8s.io   false        ValidatingWebhookConfiguration
customresourcedefinitions         crd,crds         apiextensions.k8s.io           false        CustomResourceDefinition
apiservices                                        apiregistration.k8s.io         false        APIService
applications                                       app.k8s.io                     true         Application
controllerrevisions                                apps                           true         ControllerRevision
daemonsets                        ds               apps                           true         DaemonSet
deployments                       deploy           apps                           true         Deployment
replicasets                       rs               apps                           true         ReplicaSet
statefulsets                      sts              apps                           true         StatefulSet
workflows                         wf               argoproj.io                    true         Workflow
tokenreviews                                       authentication.k8s.io          false        TokenReview
localsubjectaccessreviews                          authorization.k8s.io           true         LocalSubjectAccessReview
selfsubjectaccessreviews                           authorization.k8s.io           false        SelfSubjectAccessReview
selfsubjectrulesreviews                            authorization.k8s.io           false        SelfSubjectRulesReview
subjectaccessreviews                               authorization.k8s.io           false        SubjectAccessReview
horizontalpodautoscalers          hpa              autoscaling                    true         HorizontalPodAutoscaler
cronjobs                          cj               batch                          true         CronJob
jobs                                               batch                          true         Job
certificatesigningrequests        csr              certificates.k8s.io            false        CertificateSigningRequest
leases                                             coordination.k8s.io            true         Lease
events                            ev               events.k8s.io                  true         Event
daemonsets                        ds               extensions                     true         DaemonSet
deployments                       deploy           extensions                     true         Deployment
ingresses                         ing              extensions                     true         Ingress
networkpolicies                   netpol           extensions                     true         NetworkPolicy
podsecuritypolicies               psp              extensions                     false        PodSecurityPolicy
replicasets                       rs               extensions                     true         ReplicaSet
pytorchjobs                                        kubeflow.org                   true         PyTorchJob
scheduledworkflows                swf              kubeflow.org                   true         ScheduledWorkflow
studyjobs                                          kubeflow.org                   true         StudyJob
tfjobs                                             kubeflow.org                   true         TFJob
compositecontrollers              cc,cctl          metacontroller.k8s.io          false        CompositeController
controllerrevisions                                metacontroller.k8s.io          true         ControllerRevision
decoratorcontrollers              dec,decorators   metacontroller.k8s.io          false        DecoratorController
alertmanagers                                      monitoring.coreos.com          true         Alertmanager
prometheuses                                       monitoring.coreos.com          true         Prometheus
prometheusrules                                    monitoring.coreos.com          true         PrometheusRule
servicemonitors                                    monitoring.coreos.com          true         ServiceMonitor
networkpolicies                   netpol           networking.k8s.io              true         NetworkPolicy
poddisruptionbudgets              pdb              policy                         true         PodDisruptionBudget
podsecuritypolicies               psp              policy                         false        PodSecurityPolicy
clusterrolebindings                                rbac.authorization.k8s.io      false        ClusterRoleBinding
clusterroles                                       rbac.authorization.k8s.io      false        ClusterRole
rolebindings                                       rbac.authorization.k8s.io      true         RoleBinding
roles                                              rbac.authorization.k8s.io      true         Role
priorityclasses                   pc               scheduling.k8s.io              false        PriorityClass
storageclasses                    sc               storage.k8s.io                 false        StorageClass
volumeattachments                                  storage.k8s.io                 false        VolumeAttachment

将ServicesAccount与ClusterRole绑定

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
  name: cluster-role-all-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-role-all
subjects:
- kind: ServiceAccount
  name: sa-all
  namespace: test-namespace

使用方式

在你使用的test-namespace命名空间中的所有的工作负载当中都可以使用ServiceAccount。

在Pod当中使用

如果当前工作负载未绑定ServiceAccount,则会自动绑定defaultServiceAccount。

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: test-namespace
spec:
  serviceAccountName: sa-all
  automountServiceAccountToken: false
  ...

另外一种方式,还可以通过文件卷挂载的方式使用

apiVersion: v1
kind: Pod
metadata:
  name: test-pod
  namespace: test-namespace
spec:
  containers:
  - image: nginx
    name: nginx
    volumeMounts:
    - mountPath: /var/run/secrets/tokens
      name: vault-token
  serviceAccountName: sa-all
  volumes:
  - name: vault-token
    projected:
      sources:
      - serviceAccountToken:
          path: vault-token
          expirationSeconds: 7200 # 过期时间
          audience: vault

kubernetes会替 Pod 请求令牌并将其保存起来,通过将令牌存储到一个可配置的 路径使之在 Pod 内可用,并在令牌快要到期的时候刷新它。 kubelet 会在令牌存在期达到其 TTL 的 80% 的时候或者令牌生命期超过 24 小时 的时候主动轮换它。

参考文献

https://www.orchome.com/1315

https://www.orchome.com/1308

你的答案

查看kubernetes相关的其他问题或提一个您自己的问题
提问