如何编写shell脚本获取kubernetes集群的pod状态

t2a7ltrp  于 2023-06-05  发布在  Kubernetes
关注(0)|答案(3)|浏览(227)

在我的k8集群中,我运行的pod名称包含单词“inventory”(实际上是2 pod),我需要写一个shell脚本来删除部署并重新部署,然后它应该检查特定的pod是否正在运行,然后显示一条消息。这就是我所尝试的。

#!/bin/bash
cd /apps/application/application_yamls_develop/deployment-artifacts/inventory-service
kubectl delete -f inventory-service.yaml -n back-end
kubectl apply -f inventory-service.yaml -n back-end
sleep 20

pod_name="inventory"
namespace="back-end"

# Get the pod status
pod_status=$(kubectl get pods -n "$namespace" -o jsonpath="{.items[?(@.metadata.name.includes('$pod_name'))].status.phase}")

# Check if any matching pod is running
if [[ -n "$pod_status" ]]; then
  echo "Pod running"
else
  echo "Pod not running"
fi

但这是给bellow错误。

error: error parsing jsonpath {.items[?(@.metadata.name.includes('inventory'))].status.phase}, unclosed array expect ]

有人能指出这个问题吗?
谢谢..!

2j4z5cfb

2j4z5cfb1#

你能试试这个吗

#!/bin/bash

pod_name="devopslk"
namespace="devops"

# Get the pod status
pod_status=$(kubectl get pod "$pod_name" -n "$namespace" -o jsonpath='{.status.phase}')

# Check if any matching pod is running
if [[ -n "$pod_status" ]]; then
  echo "Pod running"
else
  echo "Pod not running, Current status: $pod_status"
fi

xytpbqjk

xytpbqjk2#

在k8s docs中找到答案

# kubectl does not support regular expressions for JSONpath output
# The following command does not work
kubectl get pods -o jsonpath='{.items[?(@.metadata.name=~/^test$/)].metadata.name}'

# The following command achieves the desired result
kubectl get pods -o json | jq -r '.items[] | select(.metadata.name | test("test-")).spec.containers[].image'

filter语句中的部分名称将不起作用,您必须在此处设置完整的pod名称:

$ k -n $ns get po -o jsonpath='{.items[?(@.metadata.name=="test")].metadata.name}'

$ k -n $ns get po -o jsonpath='{.items[?(@.metadata.name=="test-56b87dd7dc-4fcwn")].metadata.name}' 
test-56b87dd7dc-4fcwn

所以首先你需要得到所有的pod和grep他们一些如何得到所需的pod,然后检查它的状态。或者按照k8s文档中的建议使用jq
或者同时获取名称和状态:

$ k -n $ns get po -o jsonpath="{range .items[*]}[{.metadata.name},{.status.phase}]{'\n'}{end}" |\
    grep -Ei ".*$pod_name.*running" || echo fail

然后grep需要pod,你会得到状态。

csbfibhn

csbfibhn3#

这可以通过使用以下脚本中指定的pod标签来实现(相应地修改由您提供)

#!/bin/bash
#Namespace Name
namespace="backend"
#Provide label name which is specified in pod definition
appname="inventory"

# Get the pod name
pod_name=$(kubectl get pod -n $namespace -l app=$appname -o=jsonpath="{range .items[*]}{.metadata.name}")

# Get the pod status
pod_status=$(kubectl get pods -n $namespace -o=jsonpath="{.items[?(@.metadata.name == '$pod_name')].status.phase}")

# Check if any matching pod is running
if [[ ! -z "$pod_status" ]]; then
  echo "Pod running"
else
  echo "Pod not running"
fi

相关问题