问题
In the first yaml below, the second podSelector
clause (under to
) seems correctly formatted, with two spaces indent for matchLabels
, consistent with standards and the rest of the yaml.
The second yaml is identical, but matchLabels
has four spaces. This format follows the Kubernetes documentation. (There are no tabs.)
Yet the first yaml fails kubectl
validation with error validating "p.yaml": error validating data: ValidationError(NetworkPolicy.spec.egress[0].to[0]): unknown field "matchLabels" in io.k8s.api.networking.v1.NetworkPolicyPeer, and the second passes validation.
This does not pass validation:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: internal-policy
spec:
podSelector:
matchLabels:
name: internal
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
name: mysql
This passes validation:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: internal-policy
spec:
podSelector:
matchLabels:
name: internal
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
name: mysql
回答1:
Well apparently matchLabels
should be a key in the mapping value of podSelector
, hence it must be more indented. This:
- podSelector:
matchLabels:
Places matchLabels
on the same indentation level as podSelector
, since the initial -
is treated as part of the indentation as per YAML spec. Basically, there are two indentation levels defined here:
- The level of the sequence, starting with
-
. All subsequent sequence items must have their-
at the same level. - The level of the mapping which is a value of the sequence, starting with
p
. All subsequent keys of the mapping must start at the same level.
Therefore, if you want matchLabels
to be nested in podSelector
, you must indent it more:
- podSelector:
matchLabels:
回答2:
The docs are wrong then. The matchLabels is indeed a child key of a hash under podSelector. Please open an issue on the docs so we can fix it :)
来源:https://stackoverflow.com/questions/61039882/why-is-the-apparently-malformed-yaml-the-one-that-validates