在服务的所有 kubernetes pod 上运行命令 [英] Running a command on all kubernetes pods of a service

查看:20
本文介绍了在服务的所有 kubernetes pod 上运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在运行一个 kubernetes 集群,我想在属于特定服务的所有 pod 上运行一个命令.

Hey I'm running a kubernetes cluster and I want to run a command on all pods that belong to a specific service.

据我所知,kubectl exec 只能在一个 pod 上运行,并且跟踪我所有的 pod 是一项荒谬的工作(这是服务的好处之一).

As far as I know kubectl exec can only run on a pod and tracking all my pods is a ridiculous amount of work (which is one of the benefits of services).

是否有任何方法或工具可以让您广播"到服务中的所有 pod?

Is there any way or tool that gives you the ability to "broadcast" to all pods in a service?

提前感谢您的帮助!

推荐答案

正如 Bal Chua 所写,kubectl 有没办法做到这一点,但你可以使用 bash 脚本来做到这一点:

As Bal Chua wrote, kubectl has no way to do this, but you can use bash script to do this:

 #!/usr/bin/env bash

PROGNAME=$(basename $0)

function usage {
    echo "usage: $PROGNAME [-n NAMESPACE] [-m MAX-PODS] -s SERVICE -- COMMAND"
    echo "  -s SERVICE   K8s service, i.e. a pod selector (required)"
    echo "     COMMAND   Command to execute on the pods"
    echo "  -n NAMESPACE K8s namespace (optional)"
    echo "  -m MAX-PODS  Max number of pods to run on (optional; default=all)"
    echo "  -q           Quiet mode"
    echo "  -d           Dry run (don't actually exec)"
}

function header {
    if [ -z $QUIET ]; then
        >&2 echo "###"
        >&2 echo "### $PROGNAME $*"
        >&2 echo "###"
    fi
}

while getopts :n:s:m:qd opt; do
    case $opt in
        d)
            DRYRUN=true
            ;;
        q)
            QUIET=true
            ;;
        m)
            MAX_PODS=$OPTARG
            ;;
        n)
            NAMESPACE="-n $OPTARG"
            ;;
        s)
            SERVICE=$OPTARG
            ;;
        ?)
            usage
            exit 0
            ;;
    esac
done

if [ -z $SERVICE ]; then
    usage
    exit 1
fi

shift $(expr $OPTIND - 1)

while test "$#" -gt 0; do
    if [ "$REST" == "" ]; then
        REST="$1"
    else
        REST="$REST $1"
    fi

    shift
done

if [ "$REST" == "" ]; then
    usage
    exit 1
fi

PODS=()

for pod in $(kubectl $NAMESPACE get pods --output=jsonpath={.items..metadata.name}); do
    echo $pod | grep -qe "^$SERVICE" >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        PODS+=($pod)
    fi
done

if [ ${#PODS[@]} -eq 0 ]; then
    echo "service not found in ${NAMESPACE:-default}: $SERVICE"
    exit 1
fi

if [ ! -z $MAX_PODS ]; then
    PODS=("${PODS[@]:0:$MAX_PODS}")
fi

header "{pods: ${#PODS[@]}, command: "$REST"}"

for i in "${!PODS[@]}"; do
    pod=${PODS[$i]}
    header "{pod: "$(($i + 1))/${#PODS[@]}", name: "$pod"}"

    if [ "$DRYRUN" != "true" ]; then
        kubectl $NAMESPACE exec $pod -- $REST
    fi
done

这篇关于在服务的所有 kubernetes pod 上运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆