解决GitLab CI/CD在Kubernetes集群中部署出现的权限问题

110次阅读
没有评论

问题描述

在将现有的Kubernetes集群集成到GitLab实例(Omnibus版)时,在CI/CD流水线的部署阶段遇到了以下错误:

Error from server (Forbidden): error when retrieving current configuration of: Resource: "apps/v1, Resource=deployments", GroupVersionKind: "apps/v1, Kind=Deployment" Name: "test-deployment", Namespace: "default" ... User "system:serviceaccount:kubetest-2-bina:kubetest-2-bina-service-account" cannot get resource "deployments" in API group "apps" in the namespace "default" ERROR: Job failed: exit status 1

用户提供了相关的配置文件,包括.gitlab-ci.yaml、Deployment文件以及创建的ServiceAccount和ClusterRoleBinding等信息。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

更新ClusterRole配置

根据用户提供的信息,错误表明ClusterRole没有被正确配置以允许访问deployments资源。以下是更新ClusterRole和ClusterRoleBinding的步骤。

  1. 首先,更新ServiceAccount的定义,确保它被正确绑定到ClusterRole。这里我们假设ServiceAccount的名称是gitlab-admin,命名空间为kube-system
apiVersion: v1
kind: ServiceAccount
metadata:
  name: gitlab-admin
  namespace: kube-system
  1. 更新ClusterRoleBinding,将ClusterRole绑定到ServiceAccount。
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: gitlab-admin-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: deployment-reader
subjects:
- kind: ServiceAccount
  name: gitlab-admin
  namespace: kube-system
  1. 新建一个ClusterRole,用于授予对deployments资源的访问权限。
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: deployment-reader
rules:
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["get", "watch", "list"]

验证访问权限

完成以上配置后,你可以使用以下命令验证ServiceAccount是否能够在默认命名空间下访问deployments资源:

kubectl get deployments --as system:serviceaccount:kube-system:gitlab-admin -n default

结论

通过更新ClusterRole和ClusterRoleBinding配置,你可以解决GitLab CI/CD在Kubernetes集群中部署过程中出现的权限问题。这将确保你的ServiceAccount有权访问deployments资源,从而避免类似的错误。如果你在配置过程中遇到问题,可以参考本解决方案中提供的步骤逐一排查。

请注意,根据Kubernetes版本和配置的不同,可能需要进行适当的调整。在进行更改之前,请务必备份相关配置,以防不可预料的问题。

希望本解决方案对你有所帮助。如果你有任何进一步的问题或需要更多的帮助,请随时提问。

正文完