我有运行带有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": {}
    }
}

我试图获取仅包含“http”端口的输出:
$ kubectl get service elasticsearch --output jsonpath={.spec.ports[*].nodePort}
31041 31987

除了我按照备忘单此处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 `('

最佳答案

()在bash中表示某些含义(请参阅subshell),因此您的shell解释器首先这样做,并且感到困惑。将参数用单引号括起来到jsonpath,这将解决该问题:

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

例如:
# 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

10-04 11:28