最近在編寫(xiě)腳本的時(shí)候發(fā)現(xiàn)一個(gè)問(wèn)題正歼,在執(zhí)行kubectl -n kube-system get pods
這個(gè)命令的時(shí)候局义,通過(guò)ssh root@ip command
和ssh root@ip command
登錄后執(zhí)行得到了不同的結(jié)果,
-
ssh root@ip command
下結(jié)果:
[root@test1 ~]# ssh root@111.111.111.111'kubectl -n kube-system get pods'
error: the server doesn't have a resource type "pods"
-
ssh root@ip command
登錄后執(zhí)行命令:
[root@test3 ~]# kubectl -n kube-system get pods
NAME READY STATUS RESTARTS AGE
coredns-fb8b8dccf-5px49 1/1 Running 0 161d
coredns-fb8b8dccf-tdlbd 1/1 Running 0 161d
etcd-test3.weikayuninternal.com 1/1 Running 2 191d
kube-apiserver-test3.weikayuninternal.com 1/1 Running 1 191d
kube-controller-manager-test3.weikayuninternal.com 1/1 Running 2 191d
kube-flannel-ds-amd64-nj5vz 1/1 Running 0 161d
kube-proxy-vbm7c 1/1 Running 0 161d
kube-scheduler-test3.weikayuninternal.com 1/1 Running 2 191d
kubernetes-dashboard-5f7b999d65-87bnk 1/1 Running 0 161d
從上面可以看到SSH遠(yuǎn)程執(zhí)行獲取pods失敗了诅挑,但是shell窗口執(zhí)行卻成功了拔妥,所以我們可以猜到兩者之間一定有什么區(qū)別導(dǎo)致結(jié)果的不同铺厨。那么區(qū)別在哪里呢?通過(guò)研究發(fā)現(xiàn)兩者的環(huán)境變量存在區(qū)別,通過(guò)執(zhí)行printenv可以查看所有設(shè)置的環(huán)境變量:
-
ssh root@ip command
:
[root@iZ23ozpjtzfZ ~]# ssh root@111.111.111.111 'printenv'
root@111.111.111.111's password:
...
USER=root
...
-
ssh root@ip
登錄后執(zhí)行命令:
[root@test3 ~]# printenv
...
USER=root
KUBECONFIG=/etc/kubernetes/admin.conf
...
通過(guò)上面可以看到SSH遠(yuǎn)程執(zhí)行的時(shí)候是沒(méi)有KUBECONFIG這個(gè)環(huán)境變量伐蒂,而Shell窗口是有的,為什么有這個(gè)區(qū)別呢缕减?這就要從Linux的bash的四種模式說(shuō)起。
bash的四種模式:
- login + interactive
- login + non-interactive
- non-login + interactive
- non-login + non-interactive
這四種模式的具體介紹大家可以通過(guò)man bash
查看裹芝,這里不過(guò)多的介紹了兄朋,我們主要看一下加載環(huán)境變量配置文件的區(qū)別:
login | interactive + non-login | non-interactive + non-login | |
---|---|---|---|
/etc/profile | A | ||
/etc/bash.bashrc | A | ||
~/.bashrc | B | ||
~/.bash_profile | B1 | ||
~/.bash_login | B2 | ||
~/.profile | B3 | ||
BASH_ENV | A |
從上面可以看出不同方式下加載的配置文件不同,那么怎么知道我們是加載了那些配置文件呢峡扩? 這里有一個(gè)驗(yàn)證的方法,就是在上面的每個(gè)配置文件中添加一句echo $/etc/profile
這樣的命令巍佑,把每個(gè)文件的路徑打印出來(lái)堕义。當(dāng)配置文件被加載時(shí)洒擦,會(huì)輸出相應(yīng)的文件名熟嫩,本例中在兩個(gè)文件中加了該命令:/etc/pfoile, ~/.bashrc,然后使用不同SSH方式執(zhí)行命令的結(jié)果如下昧狮。
-
ssh root@ip command
:
[root@iZ23ozpjtzfZ ~]# ssh root@111.111.111.111 'echo $-'
root@111.111.111.111's password:
@_/.bash_rc
只加載了.bashrc文件,未加載/etc/profile透葛。
-
ssh root@ip
登錄后執(zhí)行命令:
root@iZ23ozpjtzfZ ~]# ssh root@111.111.111.111
root@111.111.111.111's password:
Last login: Thu Nov 21 18:41:31 2019 from 10.168.81.39
Welcome to Alibaba Cloud Elastic Compute Service !
@/etc/profile
@_/.bash_rc
[root@test3 ~]# echo $-
himBH
從輸出可以看到兩個(gè)配置都加載了,而KUBECONFIG只定義在/etc/profile中贡珊,沒(méi)有定義在.bashrc文件中,所以通過(guò)ssh root@ip command
執(zhí)行時(shí)沒(méi)有拿到KUBECONFIG這個(gè)環(huán)境變量從而導(dǎo)致報(bào)錯(cuò)寒随。知道原因后我們就可以將KUBECONFIG環(huán)境變量添加到.bashrc文件即可。