用于捕获 POD 名称的 openshift 命令 programmatically/scripting

openshift commands to catch POD name programmatically/scripting

我有 pods 个空班,想处理多个空班申请。让我们像下面这样说

sh-4.2$ oc get pods

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 获取 pods

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

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

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

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

说明:为以上代码添加说明。

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

kubectl get(并扩展为 oc get)是一个非常 的多功能工具。不幸的是,在网上浏览了一段时间后,如果不依赖 awkgrep 等外部工具,您将 肯定 无法执行正则表达式。 (我知道这 不完全是 你要问的,但我想我至少会尝试看看是否可行。

话虽如此,您可以依靠一些技巧来过滤 oc get 输出,甚至不必使用外部工具(加分项,因为这种过滤发生在服务器之前点击你的本地工具)。

首先推荐运行oc get pods --show-labels,因为如果你需要的pods有合适的标签,你可以使用标签选择器来得到你想要的pods,例如:

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

第二,如果你只关心 Running pods(因为 disk-check pods 看起来像他们'已经 Completed),您可以使用字段选择器,例如:

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

最后,如果有一个特定的值,您可以通过指定自定义列将该值拉入 CLI ,然后 greping 您关心的值,例如:

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

最棒的是,如果您依赖标签选择器 and/or 字段选择器,过滤发生在服务器端以减少最终进入您最终自定义列的数据,使一切效率更高。


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

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

添加此答案以供其他人参考。 你可以这样使用。

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