我想创建一个角色来为具有上下文的帐户服务。
我的目标是能够在服务帐户的上下文中运行kubectl get pods
。
要做到这一点,我需要:
我创建了一个服务帐户:
kubectl create serviceaccount myservice
Role.yaml:
kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
namespace: development
name: my-role
rules:
- apiGroups: ["", "extensions", "apps"]
resources: ["pods"]
verbs: ["get"]
BindRole.yaml:
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: my-role-binding
namespace: development
subjects:
- kind: ServiceAccount
name: myservice
namespace: development
apiGroup: ""
roleRef:
kind: Role
name: my-role
apiGroup: ""
我希望能够在服务帐户kubectl get pods
的上下文中运行myservice
。
要创建上下文,我需要类似的内容:
kubectl config set-context myservice-context --cluster=kubernetes --user=???
但是我不能使用--user
作为服务帐户。
那我该怎么办呢?
我曾想使用kubectl config set-credentials
,但它只是创建了一个用户,并且我已经拥有服务帐户。
编辑:
这是我尝试用服务帐户的令牌创建用户,然后将其与kubectl --context=myservice-context get pods
一起使用,但是失败了:
答案 0 :(得分:2)
看来您的~/.kube/config
文件中可能缺少该群集。如果是权限问题,我希望看到error: You must be logged in to the server (Unauthorized)
或Error from server (Forbidden)
。
您看到的错误The connection to the server localhost:8080 was refused - did you specify the right host or port?
表示没有在kubeconfig中指定名称的集群。
我会检查您的kubeconfig是否包含集群名称kubernetes
和certificate-authority-data
以及相应的server
。
例如,这是我首先尝试使用无效的群集创建不存在的服务帐户,然后再次尝试使用kubeconfig
中确实存在的群集。
错误的群集名称:
kubectl config set-context service-context \
--cluster=doesnotexist \
> --namespace=default \
> --user=service-account
Context "service-context" modified.
➜ ~ kubectl --context=service-context get pods
The connection to the server localhost:8080 was refused - did you specify the right host or port?
好的群集名称:
kubectl config set-context service-context \
--cluster=exists \
--namespace=default \
--user=service-account
Context "service-context" modified.
➜ ~ kubectl --context=service-context get pods
error: You must be logged in to the server (Unauthorized)
稍后的错误将表明您的用户/权限有问题。前者会建议cluster
中不存在kubeconfig
。
编辑:
还请记住,当您使用sudo
时,它使用的/root/.kube/config
可能并不是您想要的