从 C# 访问 kubernetes 服务 docker

Accessing kubernetes service from C# docker

我正在尝试在 kuberentes 服务中使用 C# docker 访问 Kubernetes 服务。

我有一个 python docker YAML 文件,并且想通过 c# Dotnet 核心 docker 以编程方式使用相同的 YAML 创建 pod,运行 与pythondocker。我发现 Kubernetes api for dotnet core.I 创建了下面列表 pods 的代码。

using System;
using k8s;

namespace simple
{
    internal class PodList
    {
        private static void Main(string[] args)
        {
            var config = KubernetesClientConfiguration.InClusterConfig();
            IKubernetes client = new Kubernetes(config);
            Console.WriteLine("Starting Request!");

            var list = client.ListNamespacedPod("default");
            foreach (var item in list.Items)
            {
                Console.WriteLine(item.Metadata.Name);
            }

            if (list.Items.Count == 0)
            {
                Console.WriteLine("Empty!");
            }
        }
    }
}

此代码出现错误 Forbidden(“操作返回无效状态代码 'Forbidden'”)。 而不是 InClusterConfig 使用 BuildConfigFromConfigFile 代码在本地工作 environment.Is 我错过了什么?

已编辑

apiVersion: v1
kind: ServiceAccount
metadata:
  name: test-serviceaccount
  namespace: api

---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  namespace: api
  name: test-role
rules:
    - apiGroups: ["","apps","batch"]
      # "" indicates the core API group
      resources: ["deployments", "namespaces","cronjobs"]
      verbs: ["get", "list", "update", "patch","create"]  
  

  
---

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: test-binding
  namespace: api
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: test-role
subjects:
  - kind: ServiceAccount
    name: test-serviceaccount
    namespace: api

---


apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "4"
  creationTimestamp: "2019-07-04T16:05:43Z"
  generation: 4
  labels:
    app: test-console
    tier: middle-end
  name: test-console
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      app: test-console
      tier: middle-end
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: "2019-07-04T16:05:43Z"
      labels:
        app: test-console
        tier: middle-end
    spec:
      serviceAccountName: test-serviceaccount
      containers:
      - image: test.azurecr.io/tester:1.0.0
        imagePullPolicy: Always
        name: test-console
        ports:
        - containerPort: 80
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      imagePullSecrets:
      - name: pull
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      
C# code

  client.CreateNamespacedCronJob(jobmodel, "testnamesapce");
crone job
 'apiVersion': 'batch/v1beta1',
    'kind': 'CronJob',
    'metadata': {
        'creationTimestamp': '2020-08-04T06:29:19Z',
        'name': 'forcaster-cron',
        'namespace': 'testnamesapce'
    },

InClusterConfig 使用您部署 pod 的命名空间的 default 服务帐户。默认情况下,该服务帐户不会有任何 RBAC,这会导致 Forbidden 错误。

它在本地环境中工作的原因是因为它使用来自 kubeconfig 文件的凭据,该文件大部分时间是对集群具有根级 RBAC 权限的管理员凭据。

您需要定义一个 Role 并使用 RoleBinding

将该角色附加到服务帐户

因此,如果您在 default 命名空间中部署 pod,那么下面的 RBAC 应该可以工作。

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: myrole
  namespace: default
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - list
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: role-binding
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: myrole
subjects:
- kind: ServiceAccount
  name: default
  namespace: default

一旦你申请了以上 RBAC,你可以使用下面的命令检查服务帐户的权限

kubectl auth can-i list pods --as=system:serviceaccount:default:default -n default
yes