最新文章

kubectl foreach 在多个集群中执行 kubectl 命令

kubectl foreach 在多个集群中执行 kubectl 命令

上周在写 K8s 多集群的流量调度 的 demo 部分时需要不停地在多个集群中安装组件、部署应用,或者执行各种命令。当时是通过 Linux shell 脚本并通过工具 kubectx 进行集群的切换,像这样:

或者这样:

操作繁琐,很是痛苦。

今天偶然间发现了一个 kubectl 插件 kubectl foreach ,可以在多个集群(contexts)上执行 kubectl 命令。比如 kubectl foreach cluster-1 cluster-2 -- get po -n kube-system

插件安装和使用很简单,通过 krew 进行安装:

kubectl krew install foreach

使用也很简单:

kubectl foreach -h
Usage:
    kubectl foreach [OPTIONS] [PATTERN]... -- [KUBECTL_ARGS...]

Patterns can be used to match context names from kubeconfig:
      (empty): matches all contexts
         NAME: matches context with exact name
    /PATTERN/: matches context with regular expression
        ^NAME: remove context with exact name from the matched results
   ^/PATTERN/: remove contexts matching the regular expression from the results

Options:
    -c=NUM     Limit parallel executions (default: 0, unlimited)
    -I=VAL     Replace VAL occurring in KUBECTL_ARGS with context name
    -q         Disable and accept confirmation prompts ($KUBECTL_FOREACH_DISABLE_PROMPTS)
    -h/--help  Print help

Examples:
    # get nodes on contexts named a b c
    kubectl foreach a b c -- get nodes

    # get nodes on all contexts named c0..9 except c1 (note the escaping)
    kubectl foreach '/^c[0-9]/' ^c1	 -- get nodes

    # get nodes on all contexts that has "prod" but not "foo"
    kubectl foreach /prod/ ^/foo/ -- get nodes

    # use 'kubectl tail' plugin to follow logs of pods in contexts named *test*
    kubectl foreach -I _ /test/ -- tail --context=_ -l app=foo

接下来测试下,使用 k3d 创建 3 个集群 (k3d 貌似不支持同时创建多个集群,还是需要 for 脚本来操作):