我正在尝试将kubectl auth can-i
逻辑合并到我的代码库中,但是当代码运行时,结果不是我所期望的。
我有 2 个用户(minikube / jenny)。minikube具有完整的集群范围访问权限,但jenny仅限于命名空间角色/角色绑定:
kubectl create role "jenny-pod-creator" --verb=create --resource=pod -n "jenny"
kubectl create rolebinding "jenny-creator-binding" --role="jenny-pod-creator" --user="jenny" --namespace="jenny"
使用 cli,我得到了我期望的结果:
$ kubectl auth can-i create pod --context jenny -n jenny
yes
$ kubectl auth can-i create pod --context jenny -n default
no - RBAC: role.rbac.authorization.k8s.io "jenny-pod-creator" not found
但在我的代码中,珍妮没有提出创建权限。response.Status.Allowed
始终false
适用于jenny (对于minikube始终适用)
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
authorizationv1 "k8s.io/api/authorization/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
kubeconfig := filepath.Join(
os.Getenv("HOME"), ".kube", "config",
)
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
a := clientset.AuthorizationV1().SelfSubjectAccessReviews()
sar := &authorizationv1.SelfSubjectAccessReview{
Spec: authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: "jenny",
Verb: "create",
Resource: "Pod",
},
},
}
response, err := a.Create(context.TODO(), sar, metav1.CreateOptions{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("create resource POD is %v \n", response.Status.Allowed)
}