#kubernetes
#kubernetes
Вопрос:
Я создаю учетную запись службы, роль и привязку роли, которая привязывает роль к SA.
Я пытаюсь заставить учетную запись службы перечислять узлы, но я не могу, хотя вызов auth говорит мне, что я могу (для развертываний это еще хуже, роль разрешает это, но я ничего не могу сделать):
#pods
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test auth can-i get pods
yes
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test get pods
NAME READY STATUS RESTARTS AGE
no-st-1 0/1 CreateContainerConfigError 0 74m <<--ignore the ConfigError, this is expected.
# nodes
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test auth can-i get nodes
Warning: resource 'nodes' is not namespace scoped
yes <<<<------ ?? i can get nodes, but then i can't??
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test get nodes
Error from server (Forbidden): nodes is forbidden: User "system:serviceaccount:psp-ns:sa-test" cannot list resource "nodes" in API group "" at the cluster scope
#deployments (at least this one is consistent, although the role should allow this)
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test auth can-i get deployments
no
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test get deployments
Error from server (Forbidden): deployments.apps is forbidden: User "system:serviceaccount:psp-ns:sa-test" cannot list resource "deployments" in API group "apps" in the namespace "psp-ns"
Роль, которую я использую, должна разрешать все 3 операции, описанные выше:
Simons-MBP:psp simon$ kubectl describe role test-sa-role
Name: test-sa-role
Labels: <none>
Annotations: kubectl.kubernetes.io/last-applied-configuration:
{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"Role","metadata":{"annotations":{},"name":"test-sa-role","namespace":"psp-ns"},"rules...
PolicyRule:
Resources Non-Resource URLs Resource Names Verbs
--------- ----------------- -------------- -----
deployments [] [] [list get]
nodes [] [] [list get]
pods [] [] [list get]
И, наконец, привязка роли, показывающая, что роль привязана к этой учетной записи службы:
Simons-MBP:psp simon$ kubectl describe rolebinding rb-test
Name: rb-test
Labels: <none>
Annotations: kubectl.kubernetes.io/last-applied-configuration:
{"apiVersion":"rbac.authorization.k8s.io/v1","kind":"RoleBinding","metadata":{"annotations":{},"name":"rb-test","namespace":"psp-ns"},"rol...
Role:
Kind: Role
Name: test-sa-role
Subjects:
Kind Name Namespace
---- ---- ---------
ServiceAccount sa-test psp-ns
Почему это происходит? Я ожидал, что смогу получить все узлы / модули / развертывания, и это auth can-i
возвращает yes
для всех вызовов, которые я пробовал.
Комментарии:
1.
deployments
они находятся вapps
группе API, поэтому, если они естьapiGroups: [""]
в вашемRole
определении, это не сработает. Вы можете использовать либоapiGroups: ["", "apps"]
илиapiGroups: ["*"]
, либо добавить дополнительное правило дляdeployments
withapiGroups: ["apps"]
.
Ответ №1:
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test auth can-i get nodes
Приведенная выше команда просто проверяет, что является ClusterRole
, Role
и RoleBinding
определенным, и поскольку у вас есть Role
который предоставляет доступ к узлу, он возвращает yes
. На самом деле это не учитывает тот факт, что node
является ресурсом, управляемым кластером, и, следовательно, должно быть ClusterRole
вместо Role
.
Возвращаясь к тому, почему вы не можете получить доступ к deployment, это потому, что у вас может быть apiGroups: [""]
роль, но развертывания находятся в apps
группе API. Также используйте пространство имен psp-ns
явно в команде
Simons-MBP:psp simon$ kubectl --as=system:serviceaccount:psp-ns:sa-test auth can-i get deployments -n psp-ns
Чтобы иметь возможность доступа, node
вам нужно ClusterRole
вместо Role
because node
является ресурсом, управляемым кластером.
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
# "namespace" omitted since ClusterRoles are not namespaced
name: node-clusterrole
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "watch", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: psp-ns
name: deployment-role
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "watch", "list"]
И затем
- Создайте
RoleBinding
илиClusterRoleBinding
для привязки вышеуказанной кластерной ролиnode-clusterrole
к учетной записи службы. - Создайте,
RoleBinding
чтобы привязать вышеуказанную рольdeployment-role
к учетной записи службы
Комментарии:
1. это сработало просто отлично, хотя и не дает ответа на вопрос, почему я не могу «получить» развертывания, поскольку развертывания представляют собой ресурсы с пространством имен
2. Отредактируйте вопрос, чтобы добавить все ролевые и ролевые привязки yamls
Ответ №2:
Учетные записи служб имеют пространство имен. Из документации kubernetes https://kubernetes.io/docs/reference/access-authn-authz/authentication / в котором говорится
In contrast, service accounts are users managed by the Kubernetes API. They are bound to specific namespaces, and created automatically by the API server or manually through API calls.
API-ресурсы с пространством имен
kubectl api-resources --namespaced=true
NAME SHORTNAMES APIGROUP NAMESPACED KIND
bindings true Binding
configmaps cm true ConfigMap
endpoints ep true Endpoints
events ev true Event
limitranges limits true LimitRange
persistentvolumeclaims pvc true PersistentVolumeClaim
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
controllerrevisions apps true ControllerRevision
daemonsets ds apps true DaemonSet
deployments deploy apps true Deployment
replicasets rs apps true ReplicaSet
statefulsets sts apps true StatefulSet
localsubjectaccessreviews authorization.k8s.io true LocalSubjectAccessReview
horizontalpodautoscalers hpa autoscaling true HorizontalPodAutoscaler
cronjobs cj batch true CronJob
jobs batch true Job
leases coordination.k8s.io true Lease
endpointslices discovery.k8s.io true EndpointSlice
events ev events.k8s.io true Event
ingresses ing extensions true Ingress
ingresses ing networking.k8s.io true Ingress
networkpolicies netpol networking.k8s.io true NetworkPolicy
poddisruptionbudgets pdb policy true PodDisruptionBudget
rolebindings rbac.authorization.k8s.io true RoleBinding
roles rbac.authorization.k8s.io true Role
API-ресурсы без пространства имен
kubectl api-resources --namespaced=false
NAME SHORTNAMES APIGROUP NAMESPACED KIND
componentstatuses cs false ComponentStatus
namespaces ns false Namespace
nodes no false Node
persistentvolumes pv false PersistentVolume
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
tokenreviews authentication.k8s.io false TokenReview
selfsubjectaccessreviews authorization.k8s.io false SelfSubjectAccessReview
selfsubjectrulesreviews authorization.k8s.io false SelfSubjectRulesReview
subjectaccessreviews authorization.k8s.io false SubjectAccessReview
certificatesigningrequests csr certificates.k8s.io false CertificateSigningRequest
ingressclasses networking.k8s.io false IngressClass
runtimeclasses node.k8s.io false RuntimeClass
podsecuritypolicies psp policy false PodSecurityPolicy
clusterrolebindings rbac.authorization.k8s.io false ClusterRoleBinding
clusterroles rbac.authorization.k8s.io false ClusterRole
priorityclasses pc scheduling.k8s.io false PriorityClass
csidrivers storage.k8s.io false CSIDriver
csinodes storage.k8s.io false CSINode
storageclasses sc storage.k8s.io false StorageClass
volumeattachments storage.k8s.io false VolumeAttachment
И УЗЛЫ являются ресурсами кластера, а не пространством имен. Вы можете попробовать clusterrole и clusterrolebinding с учетной записью службы.