【问题标题】:Print the namespace of the current context in Kubernetes打印 Kubernetes 中当前上下文的命名空间
【发布时间】:2021-02-24 21:08:31
【问题描述】:

我想在 Kubernetes 中打印当前上下文的命名空间。

oc config view -o json 返回以下输出(为便于阅读而缩短)

{
    "kind": "Config",
    "apiVersion": "v1",
    "contexts": [
        {
            "name": "pp2-review/master-ocp-internal-company-com:443/Philippe",
            "context": {
                "cluster": "master-ocp-internal-company-com:443",
                "user": "Philippe",
                "namespace": "pp2-review"
            }
        },
        {
            "name": "pp2-master/master-ocp-internal-company-com:443/Philippe",
            "context": {
                "cluster": "master-ocp-internal-company-com:443",
                "user": "Philippe",
                "namespace": "review"
            }
        }
    ],
    "current-context": "pp2-review/master-ocp-internal-company-com:443/Philippe"
}

我想返回pp2-review。当前上下文的命名空间。

oc config view -o "jsonpath={\$.current-context}" 返回pp2-review/master-ocp-internal-company-com:443/Philippe

oc config view -o "jsonpath={.contexts[?(@.name==\"pp2-review/master-ocp-internal-company-com:443/Philippe\")].context.namespace}" 返回pp2-review

将它们组合成 oc config view -o "jsonpath={\$.contexts[?(@.name==\$.current-context)]}" 不会返回任何内容。

除了执行第一个命令并将其返回值放在第二个之外,还有其他方法吗?

【问题讨论】:

  • 我不能尝试这个,但我认为这个路径快递应该可以工作:$..[?(@.name==$.current-context)].context.namespace
  • 执行返回error: error executing jsonpath "{$..[?(@.name==$.current-context)].context.namespace}": Error executing template: … is not array or slice and cannot be filtered.
  • Welp,看来 kubectl 的 Golang JSONPath 实现不支持这个。
  • 太糟糕了。感谢您的尝试。

标签: kubectl jsonpath


【解决方案1】:

此命令将显示您当前的上下文和命名空间。 --minify 标志意味着只返回有关当前上下文的详细信息:

kubectl config view --minify

【讨论】:

    【解决方案2】:

    这应该可行:

    kubectl config view --minify | grep namespace:

    【讨论】:

      【解决方案3】:

      因为 JSON 路径似乎不起作用。我搜索并找到了使用 Go 模板的解决方案:

      > oc config view -o go-template='{{$currentContext := index . "current-context"}}{{- range .contexts -}}{{- if eq .name $currentContext -}}{{ .context.namespace}}{{- end -}}{{- end -}}'
      review
      

      【讨论】:

        【解决方案4】:

        简单的 bash 命令替换应该可以完成这项工作:

        oc config view -o "jsonpath={.contexts[?(@.name==\"$(oc config view -o "jsonpath={\$.current-context}")\")].context.namespace}"
        

        【讨论】:

        • 我知道。但如果可能的话,我想打一个电话给oc
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-25
        • 1970-01-01
        • 1970-01-01
        • 2012-02-12
        • 2019-08-14
        • 1970-01-01
        相关资源
        最近更新 更多