说,我有两个命名空间k8s-app1和k8s-app2
我可以使用以下命令列出来自特定命名空间的所有pod
kubectl get pods -n <namespace>
我们需要将命名空间附加到所有命令以列出各自命名空间中的对象。有没有办法在不显式包含命名空间的情况下设置特定的命名空间和列表对象?
我喜欢我的回答简短,中肯,并参考官方留档:
答案:
kubectl config set-context --current --namespace=my-namespace
从:
https://kubernetes.io/docs/reference/kubectl/cheatsheet/
# permanently save the namespace for all subsequent kubectl commands in that context.
kubectl config set-context --current --namespace=ggckad-s2
有几个选项:
kubectl config set-context --current --namespace=<namespace>
kubectl config set-context gce-dev --user=cluster-admin --namespace=dev
kubectl config use-context gce-dev
$ kubens kube-system
$ alias kubens='kubectl config set-context --current --namespace '
$ alias kubectx='kubectl config use-context '
// Usage
$ kubens kube-system //Switch to a different namespace
$ kubectx docker //Switch to separate context
我能够使用以下步骤切换命名空间
kubectl config set-context $(kubectl config current-context) --namespace=<namespace>
kubectl config view | grep namespace
kubectl get pods
这就是我已经测试过的
# Create namespaces k8s-app1, k8s-app2 and k8s-app3
master $ kubectl create ns k8s-app1
namespace/k8s-app1 created
master $ kubectl create ns k8s-app2
namespace/k8s-app2 created
master $ kubectl create ns k8s-app3
namespace/k8s-app3 created
# Create Service Account app1-sa in k8s-app1
# Service Account app2-sa in k8s-app2
# Service Account app3-sa in k8s-app3
master $ kubectl create sa app1-sa -n k8s-app1
serviceaccount/app1-sa created
master $ kubectl create sa app2-sa -n k8s-app2
serviceaccount/app2-sa created
master $ kubectl create sa app3-sa -n k8s-app3
serviceaccount/app3-sa created
# Switch namespace
master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app1
Context "kubernetes-admin@kubernetes" modified.
master $ kubectl config view | grep namespace
namespace: k8s-app1
master $ kubectl get sa
NAME SECRETS AGE
app1-sa 1 1m
default 1 6m
master $
master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app2
Context "kubernetes-admin@kubernetes" modified.
master $ kubectl get sa
NAME SECRETS AGE
app2-sa 1 2m
default 1 7m
master $
master $ kubectl config set-context $(kubectl config current-context) --namespace=k8s-app3
Context "kubernetes-admin@kubernetes" modified.
master $ kubectl get sa
NAME SECRETS AGE
app3-sa 1 2m
default 1 7m