用于命名路径的kubectl jsonpath表达式

Lev*_*sov 1 bash kubernetes kubectl

我有运行2个命名端口的kube服务,如下所示:

$ kubectl get service elasticsearch --output json
{
    "apiVersion": "v1",
    "kind": "Service",
    "metadata": {
        ... stuff that really has nothing to do with my question ...
    },
    "spec": {
        "clusterIP": "10.0.0.174",
        "ports": [
             {
                "name": "http",
                "nodePort": 31041,
                "port": 9200,
                "protocol": "TCP",
                "targetPort": 9200
            },
            {
                "name": "transport",
                "nodePort": 31987,
                "port": 9300,
                "protocol": "TCP",
                "targetPort": 9300
            }
        ],
        "selector": {
            "component": "elasticsearch"
        },
        "sessionAffinity": "None",
        "type": "NodePort"
    },
    "status": {
        "loadBalancer": {}
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取仅包含'http'端口的输出:

$ kubectl get service elasticsearch --output jsonpath={.spec.ports[*].nodePort}
31041 31987
Run Code Online (Sandbox Code Playgroud)

除非我在cheatsheet中添加测试表达式,这里http://kubernetes.io/docs/user-guide/kubectl-cheatsheet/的名称我得到一个错误

$ kubectl get service elasticsearch --output jsonpath={.spec.ports[?(@.name=="http")].nodePort}
-bash: syntax error near unexpected token `('
Run Code Online (Sandbox Code Playgroud)

Ami*_*pta 9

(并且)意味着bash中的某些东西(参见subshel​​l),所以你的shell解释器首先要做到这一点而感到困惑.将参数包装jsonpath在单引号中,这将修复它:

$ kubectl get service elasticsearch --output jsonpath='{.spec.ports[?(@.name=="http")].nodePort}'
Run Code Online (Sandbox Code Playgroud)

例如:

# This won't work:
$ kubectl get service kubernetes --output jsonpath={.spec.ports[?(@.name=="https")].targetPort}
-bash: syntax error near unexpected token `('

# ... but this will:
$ kubectl get service kubernetes --output jsonpath='{.spec.ports[?(@.name=="https")].targetPort}'
443
Run Code Online (Sandbox Code Playgroud)


小智 7

我在 Powershell 的 Windows 上遇到了这个问题:

执行模板时出错:无法识别的标识符 http2

在 jsonpath 中指定用双引号括起来的字符串值时 - 要解决错误,有两种方法:

交换单引号和双引号:

kubectl -n istio-system get service istio-ingressgateway -o jsonpath="{.spec.ports[?(@.name=='http2')].port}"
Run Code Online (Sandbox Code Playgroud)

或者转义双引号中封装的单引号:

kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name==\"http2\")].port}'
Run Code Online (Sandbox Code Playgroud)