Search code examples
kuberneteskubectl

kubectl: List pods whose names starting with a keyword string


Using kubectl, how can I get a list of the pods whose name starts with a particular string?

Example

My pods:

$ kubectl get pods -n kong
NAMESPACE     NAME                               READY   STATUS    RESTARTS         AGE
kong          foobar-cc7654c7b-htvmx             1/1     Running   0                19m
kong          kong-controller-549fcc4d84-s7l7b   1/1     Running   0                20m
kong          kong-gateway-699c995d4d-mf64r      1/1     Running   0                19m

I'd like to retrieve all the pods starting with "kong-":

$ kubectl get pods -n kong --no-headers <some_kind_of_selector>
kong          kong-controller-549fcc4d84-s7l7b   1/1     Running   0                20m
kong          kong-gateway-699c995d4d-mf64r      1/1     Running   0                19m

Pods labels

// kong-controller-549fcc4d84-s7l7b
{
  "app": "kong-controller",
  "app.kubernetes.io/component": "app",
  "app.kubernetes.io/instance": "kong",
  "app.kubernetes.io/managed-by": "Helm",
  "app.kubernetes.io/name": "controller",
  "app.kubernetes.io/version": "3.4",
  "helm.sh/chart": "controller-2.31.0",
  "pod-template-hash": "549fcc4d84",
  "version": "3.4"
}

// kong-gateway-699c995d4d-mf64r
{
  "app": "kong-gateway",
  "app.kubernetes.io/component": "app",
  "app.kubernetes.io/instance": "kong",
  "app.kubernetes.io/managed-by": "Helm",
  "app.kubernetes.io/name": "gateway",
  "app.kubernetes.io/version": "3.4",
  "helm.sh/chart": "gateway-2.31.0",
  "pod-template-hash": "699c995d4d",
  "version": "3.4"
}

Solution

  • The kubectl command as of now doesn’t support any type of regex filters.

    Many requests were raised for including this feature in the kubernetes source code but were rejected, I’m including those feature requests for your references below. So, as of now the only possible solution is to use either grep or awk along with kubectl commands for filtering out resources starting with a particular string.

    References:

    1. Propose LabelSelector to support Regexp operator

    2. Allow wildcards in field selectors

    3. Allow case-insensitive matching in selectors