从Pod调用Kubernetes API时收到错误

时间:2019-06-24 14:59:28

标签: kubernetes

我有已容器化的.NET Standard(4.7.2)简单应用程序。它具有列出集群中所有名称空间的方法。我使用csharp kubernetes client与API进行交互。根据{{​​3}},API服务器的默认凭据是在容器中创建的,并用于与API服务器通信,但是在从容器中调用kubernetes API时,出现以下错误:

  

操作返回了无效的状态代码“禁止”

我的部署Yaml非常小: apiVersion: v1 kind: Pod metadata: name: cmd-dotnetstdk8stest spec: nodeSelector: kubernetes.io/os: windows containers: - name: cmd-dotnetstdk8stest image: eddyuk/dotnetstdk8stest:1.0.8-cmd ports: - containerPort: 80

1 个答案:

答案 0 :(得分:2)

我认为您在集群内部激活了RBAC。您需要为包含角色的Pod分配一个ServiceAccount,使该ServerAccount可以获取所有命名空间的列表。在Pod模板中未指定ServiceAccount时,会将命名空间默认ServiceAccount分配给在此命名空间中运行的Pod。

首先,您应该创建角色

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: <YOUR NAMESPACE>
  name: namespace-reader
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["namespaces"] # Resource is namespaces
  verbs: ["get", "list"] # Allowing this roll to get and list namespaces

在您的命名空间中创建一个新的ServiceAccount

apiVersion: v1
kind: ServiceAccount
metadata:
  name: application-sa
  namespace: <YOUR-NAMESPACE>

将您的角色创建角色分配给服务帐户:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: allow-namespace-listing
  namespace: <YOUR-NAMESPACE>
subjects:
- kind: ServiceAccount
  name: application-sa # Your newly created Service-Account
  namespace: <YOUR-NAMESPACE>
roleRef:
  kind: Role
  name: namespace-reader # Your newly created Role
  apiGroup: rbac.authorization.k8s.io

通过在您的Pod规范中添加ServiceAccount将新角色分配给您的Pod:

apiVersion: v1
kind: Pod
metadata:
  name: podname
  namespace: <YOUR-NAMESPACE>
spec:
  serviceAccountName: application-sa

您可以阅读more about RBAC in the official docs。也许您想定义use kubectl-Commands instead of YAML