openshift命令以编程/脚本方式捕获POD名称



我的开放式轮班中有pod,希望处理多个开放式轮班应用程序。比如说低于

sh-4.2$oc获取吊舱

NAME                                  READY     STATUS      RESTARTS   AGE
jenkins-7fb689fc66-fs2xb              1/1       Running     0          4d
jenkins-disk-check-1587834000         0/1       Completed   0          21h
NAME                                 READY     STATUS    RESTARTS   AGE
jenkins-7fb689fc66-gsz9j              0/1       Running   735        9d
jenkins-disk-check-1587834000    
NAME                                READY     STATUS    RESTARTS   AGE
jenkins-9euygc66-gsz9j               0/1       Running   735        9d

我试过使用以下命令

oc获取吊舱

export POD=$(oc get pods | awk '{print $1}' | grep jenkins*)

我想使用脚本找到以数字"jenkins-7fb689fc66-fs2xb"、jenkins-9euygc66-gsz9j等开头的pod,并且需要忽略磁盘检查pod。如果我捕捉到上面的pod,并且需要通过编程执行终端并运行一些shell命令。有人能帮我吗?

kubectl get(以及扩展oc get(是一个非常通用的工具。不幸的是,在网上浏览了一段时间后,如果不依赖awkgrep等外部工具,您肯定无法执行Regex。(我知道这并不是你所问的,但我想我至少应该试着看看这是否可能

话虽如此,在您甚至需要引入外部工具之前,您可以依靠一些技巧来过滤oc get输出(奖励积分,因为这种过滤在服务器上发生,甚至在它到达您的本地工具之前(。

首先建议运行oc get pods --show-labels,因为如果你需要的pod被适当地标记,你可以使用标签选择器来获得你想要的pod,例如:

oc get pods --selector name=jenkins
oc get pods --selector <label_key>=<label_value>

第二个,如果你只关心Running吊舱(因为disk-check吊舱看起来已经是Completed了(,你可以使用字段选择器,例如:

oc get pods --field-selector status.phase=Running
oc get pods --field-selector <json_path>=<json_value>

最后,如果您想要一个特定的值,您可以通过指定自定义列将该值拉入CLI,然后对您关心的值执行grep操作,例如:

oc get pods -o custom-columns=NAME:.metadata.name,TYPES:.status.conditions[*].type | grep "Ready"

最好的是,如果您依赖标签选择器和/或字段选择器,则会在服务器端进行筛选,以减少最终进入最终自定义列的数据,从而使一切都更加高效。


对于特定的用例,似乎只使用--field-selector就足够了,因为disk-check吊舱已经是Completed了。因此,如果没有关于Jenkins pod的JSON是如何构建的的更多信息,这对您来说应该足够好了:

oc get pods --field-selector status.phase=Running

假设您需要在第一个字段中打印jenkins id,您可以尝试以下操作吗。

awk 'match($0,/jenkins[^ ]*/){print substr($0,RSTART,RLENGTH)}' Input_file

解释:添加对上述代码的解释。

awk '                                ##Starting awk program from here.
match($0,/jenkins[^ ]*/){            ##Using match function in which mentioning regex jenkins till spacein current line.
print substr($0,RSTART,RLENGTH)    ##Printing sub-string in current line where starting point is RSTART till RLENGTH value.
}
' Input_file                         ##Mentioning Input_file name here.

添加此答案供其他人参考。你可以用这种方式。

export POD=$(oc get pods | awk '{print $1}' | grep jenkins* | grep -v jenkins-disk-check)

最新更新