我可以使用 kubectl 查找设置了关联性的部署吗?

Can I use kubectl to find deployments that have affinities set?

我想验证一下,具有 Pod 和 NodeAffinities (+AntiAffinity) 的部署是根据内部指南配置的。

是否有可能使用 kubectl 进行部署(或 Pods)并将结果限制为配置了此类关联的对象?

我试过 jsonpath 输出,但到目前为止没有成功。

希望您享受 Kubernetes 之旅!

如果您需要使用亲缘关系(尤其是 preferredDuringSchedulingIgnoredDuringExecution(下面的解释))并且只想“找到”实际具有亲缘关系的部署,您可以使用这个:

❯ k get deploy  -o custom-columns=NAME:".metadata.name",AFFINITIES:".spec.template.spec.affinity"
NAME                               AFFINITIES
nginx-deployment                   <none>
nginx-deployment-vanilla           <none>
nginx-deployment-with-affinities   map[nodeAffinity:map[preferredDuringSchedulingIgnoredDuringExecution:[map[preference:map[matchExpressions:[map[key:test-affinities1 operator:In values:[test1]]]] weight:1]] requiredDuringSchedulingIgnoredDuringExecution:map[nodeSelectorTerms:[map[matchExpressions:[map[key:test-affinities operator:In values:[test]]]]]]]]

每个 <none> 模式表示部署中没有关联。

但是,对于亲缘关系,如果您只想获得具有亲缘关系的部署而没有没有亲缘关系的部署,请使用此:

❯ k get deploy  -o custom-columns=NAME:".metadata.name",AFFINITIES:".spec.template.spec.affinity" | grep -v "<none>"
NAME                               AFFINITIES
nginx-deployment-with-affinities   map[nodeAffinity:map[preferredDuringSchedulingIgnoredDuringExecution:[map[preference:map[matchExpressions:[map[key:test-affinities1 operator:In values:[test1]]]] weight:1]] requiredDuringSchedulingIgnoredDuringExecution:map[nodeSelectorTerms:[map[matchExpressions:[map[key:test-affinities operator:In values:[test]]]]]]]]

如果您只想要具有相似性的部署的名称,请考虑使用这个小脚本:

❯ k get deploy  -o custom-columns=NAME:".metadata.name",AFFINITIES:".spec.template.spec.affinity" --no-headers | grep -v "<none>" | awk '{print }'
nginx-deployment-with-affinities

但是,不要忘记 nodeSelector 是将 Pods 限制到具有特定标签的节点的最简单方法。 (更多信息在这里:https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#affinity-and-anti-affinity)。还请记住(根据相同的 link)requiredDuringSchedulingIgnoredDuringExecution 类型的节点亲和力功能类似于 nodeSelector,但具有更具表现力的语法! 因此,如果您在处理关联性时不需要 preferredDuringSchedulingIgnoredDuringExecution,请考虑使用 nodeSelector !

看完上面的link,如果你想处理nodeSelector,你可以使用我之前使用的相同机制:

❯ k get deploy  -o custom-columns=NAME:".metadata.name",NODE_SELECTOR:".spec.template.spec.nodeSelector"
NAME                       NODE_SELECTOR
nginx-deployment           map[test-affinities:test]
nginx-deployment-vanilla   <none>