GitLab 连接已有 Kubernetes 集群
<p>在 gitlab 的 Amin Area 页面,打开侧边栏的 Kubernetes ,点击 Integrate with a cluster certificates,选择 Connect existing cluster,输入以下信息</p><ul>
<li>Kubernetes cluster name:输入集群名称 <code>cnblogs-production</code></li>
<li>API URL:通过 <code>kubectl cluster-info</code> 命令查看 api 地址,我们这里是 <code>https://k8s-api:6443</code></li>
<li>CA Certificate: 通过下面的命令获取证书</li>
</ul>
<pre><code class="language-bash">kubectl get secret \
$(kubectl get secrets | grep default-token | awk '{print $1}') \
-o jsonpath="{['data']['ca\.crt']}" | base64 --decode
</code></pre>
<ul>
<li>Service Token:通过以下步骤拿到 service token
<ul>
<li>创建名为 gitlab 的 service account:<code>kubectl create serviceaccount gitlab -n kube-system</code></li>
<li>将 gitlab service account 加入到 cluster-admin 角色: <code>kubectl create clusterrolebinding gitlab-cluster-admin --clusterrole=cluster-admin --serviceaccount=default:gitlab -n kube-system</code>(注:这个命令中 serviceaccount 参数写错了,不是<code>default:gitlab</code>,应该是<code>kube-system:gitlab</code>)</li>
<li>拿 service token:<code>kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep gitlab | awk '{print $1}')</code></li>
</ul>
</li>
</ul>
<p>然后点击 "Add Kubernetes cluster" 按钮进行提交,提交时报错:</p>
<blockquote>
<p>is blocked: Requests to the local network are not allowed</p>
</blockquote>
<p>报错解决方法:在 Admin Area -> Settings -> Network 中选中 "Allow requests to the local network from web hooks and services" 并保存。</p>
<p>再次提交成功。</p>
<p>在 gitlab 服务器的 hosts 文件中添加 api url 用到的主机名 k8s-api 的解析(我们搭建的是高可用集群,所以这里用的是自定义主机名)。</p>
<p>配置完成,gitlab 却连不上 k8s 集群。</p>
<img src="https://img2020.cnblogs.com/blog/1/202102/1-20210201180853002-1490773017.png" style="width: 800px">
<p>登录到 gitlab 服务器,将之前拿到的证书保存到 ca.crt 文件,用下面的 curl 命令请求 api</p>
<pre><code class="language-bash">curl --cacert ca.crt -H "Authorization: Bearer <service token>" https://k8s-api:6443/api/v1/namespaces/production/pods
</code></pre>
<p>返回的是 403 错误</p>
<pre><code class="language-json">{
"kind": "Status",
"apiVersion": "v1",
"metadata": {
},
"status": "Failure",
"message": "pods is forbidden: User \"system:serviceaccount:kube-system:gitlab\" cannot list resource \"pods\" in API group \"\" in the namespace \"production\"",
"reason": "Forbidden",
"details": {
"kind": "pods"
},
"code": 403
}
</code></pre>
<p>通过上面的错误信息找到了线索,请求 api 时使用的 service account 是 <code>kube-system:gitlab</code> ,但我们创建 ClusterRoleBinding 时用的是 <code>--serviceaccount=default:gitlab</code>,命名空间弄错了,通过下面的命令编辑 ClusterRoleBinding 配置文件,更正命名空间后问题就解决了。</p>
<pre><code class="language-bash">kubectl edit clusterrolebinding gitlab-cluster-admin -n kube-system
</code></pre>
<p>gitlab 连接 k8s 集群成功!</p>
<img src="https://img2020.cnblogs.com/blog/1/202102/1-20210201184540270-346795933.png" style="width: 800px">
<p>参考资料:</p>
<ul>
<li>Gitlab添加K8S集群</li>
<li>Connecting GitLab to Kubernetes</li>
</ul><br><br>
来源:https://www.cnblogs.com/dudu/p/14355048.html
頁:
[1]