如何显示所有 deployments/daemonsets 特定挂载 configmap/secret?

How to show all deployments/daemonsets which mount specific configmap/secret?

有时,我想探索所有 deployments/daemonsets 挂载特定 configmap/secret。

有什么方法可以通过 kubectl 实现吗?

您需要 jq 才能执行如此复杂的查询。 给你:

kubectl get -o json deploy,daemonset | jq '[.items[] | . as $parent | .spec.template.spec.volumes[]? | select(.configMap != null) | {kind:$parent.kind, name:$parent.metadata.name, configMap:.configMap.name}]'

jq命令de-constructed:

[ // output as array
  .items[] // iterate over root key 'items'
  | 
  . as $parent // store the current entry as $parent to refer to it later
  | 
  .spec.template.spec.volumes[]? // iterate over its volumes (the ? to prevent error if there is no volume
  | 
  select(.configMap != null) // select only those volumes with configMap key 
  | 
  {kind:$parent.kind, name:$parent.metadata.name, configMap:.configMap.name} // now construct the output using $parent's kind and name and the configMap's name
]

示例输出:

[
  {
    "kind": "Deployment",
    "name": "telemetry-agent",
    "configMap": "telemetry-config-map"
  },
  {
    "kind": "DaemonSet",
    "name": "fluent-bit",
    "configMap": "fluent-bit"
  },
  {
    "kind": "DaemonSet",
    "name": "telegraf",
    "configMap": "telegraf"
  }
]

N.B。如果要查找具体的configMap,只需将select()子句.configMap != null替换为.configMap.name == "specific-configmap"即可。另外,如果您想从所有命名空间

查询,请随时将--all-namespaces 添加到kubectl get 命令