✨ (helm/v2-alpha): Helm charts now include optional NetworkPolicy resources by default when none are defined in the informed Kustomize file. #5708
Hi @mattsu2020. Thanks for your PR.
I'm waiting for a kubernetes-sigs member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work.
Regular contributors should join the org to skip this step.
Once the patch is verified, the new status will be reflected by the ok-to-test label.
I understand the commands that are listed here.
<details>
Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
</details>
This change wires NetworkPolicies into extraction/categorization, but the chart generation flow still won’t emit any NetworkPolicy templates when the input manifests don’t contain NetworkPolicy resources (e.g., the default scaffolding has ../network-policy commented out in config/default/kustomization). In that common case, values.yaml will now expose networkPolicy.enable but toggling it can’t enable anything because there are no templates to render. To actually make NetworkPolicy optional via Helm values alone (as described in the PR summary/issue), consider generating a default NetworkPolicy template when none are detected (similar to the existing generic ServiceMonitor behavior) or otherwise sourcing NetworkPolicy manifests even when excluded from the kustomize output.
The ResourceCategorizer doc comment lists the supported groups but doesn’t include the newly added "network-policy" group, so it’s now inaccurate. Please update the comment to reflect the full set of groups so future maintainers don’t miss this category.
Pull request overview
This PR extends the helm/v2-alpha plugin’s Helm chart generation pipeline to recognize NetworkPolicy resources and treat them as an optional feature, mirroring the existing conditional-templating approach used for Prometheus.
Changes:
NetworkPolicy parsing, feature detection (HasNetworkPolicy), and categorization into a dedicated network-policy template group.NetworkPolicy templates with {{- if .Values.networkPolicy.enable }} guards and emit a networkPolicy.enable value in values.yaml.network-policy resources into individual template files.Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.
<details>
<summary>Show a summary per file</summary>
| File | Description |
| ---- | ----------- |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/values.go | Emit networkPolicy.enable in values.yaml based on detected resources. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/templates/values_test.go | Add unit coverage for networkPolicy.enable value emission behavior. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/templater/templater_test.go | Add tests ensuring conditional wrapping is applied (or not) for NetworkPolicy based on apiVersion. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/templater/appliers/conditionals.go | Add NetworkPolicy conditional wrapper logic keyed off kind/apiVersion. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/parser.go | Parse networking.k8s.io/v1 NetworkPolicy resources into a dedicated slice. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/parser_test.go | Add parser coverage for NetworkPolicy documents. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/generator.go | Split network-policy resources into separate files. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/kustomize/categorizer.go | Categorize NetworkPolicy resources into the network-policy group. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/extractor/features.go | Detect HasNetworkPolicy based on extracted NetworkPolicy resources. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/extractor/extractor.go | Extend ResourceSet with NetworkPolicies. |
| pkg/plugins/optional/helm/v2alpha/scaffolds/internal/chart_scaffolder.go | Wire parsed NetworkPolicies into the extractor ResourceSet. |
| pkg/plugins/optional/helm/v2alpha/internal/common/consts.go | Add NetworkPolicy kind and networking API version constants. |
</details>
I implemented this by wiring the NetworkPolicy resources into the extractor ResourceSet as NetworkPolicies: resources.NetworkPolicies.
not included in extras.
This one should be implemented at the same way of ServiceMonitor right?
If not added by default because was not find in the kustomize you wnat to have the NP scaffold in the chart. Are it done in this way? if so, why we have no change in the testdata samples? Why are we not seen the new NPs in the samples scaffolded?
Why do we need to have the condition HasWebhook here?
What is the relation of NPs with webhooks?
See all tests implemeted in the project.
All of them use
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
We should follow BBD style.
Could you please fix this one?
In this template the ingress port is hard-coded to 8443. Since the chart already exposes metrics.port and templates the metrics Service/Deployment ports via .Values.metrics.port, the NetworkPolicy should use the same value; otherwise changing metrics.port will break connectivity (policy will allow a different destination port than the pod is actually listening on).
The webhook NetworkPolicy allows port 443, but the chart templates the webhook server/container port via .Values.webhook.port (default 9443) and the Service typically uses targetPort: 9443. NetworkPolicy port matching is against the pod’s destination port (post-Service DNAT), so this should align with the webhook pod port (and be templated from .Values.webhook.port), otherwise enabling the policy will block webhook traffic.
Both policies use fixed metadata.name values (e.g. allow-metrics-traffic). That can cause name collisions when multiple Helm releases of the same chart are installed into the same namespace, and is inconsistent with other generated resources that use the chart’s helper naming (<chart>.resourceName / <chart>.fullname). Consider generating these names via the existing helper templates so they are release-scoped.
Force is defined on the template struct but is not used: SetTemplateDefaults always sets IfExistsAction = machinery.OverwriteFile regardless of Force, and the field comment implies conditional behavior. Either honor Force (like other templates do) or remove the field/comment to avoid misleading callers.
This webhook policy also uses a fixed metadata.name (allow-webhook-traffic). As with the metrics policy, this can collide across multiple Helm releases installed into the same namespace. Prefer generating the resource name via the existing helper templates so it is release-scoped and consistent with other chart resources.
Pull request overview
Copilot reviewed 15 out of 15 changed files in this pull request and generated 5 comments.
The relation is that the generic NetworkPolicy selects the controller-manager Pod and restricts ingress. If the project has webhooks, allowing only the metrics port would block webhook traffic, so we need to generate an additional webhook-specific allow policy when webhooks are detected.
the current code does not make this relationship clear enough. I will improve the comment and add/adjust tests to cover the webhook case explicitly.
We will correct the fixed value due to the issue.
I will make the necessary changes to use variables.
We will make the necessary corrections to prevent any conflicts.
Referenced other code and modified it so that Force can use it
I made the necessary adjustments to ensure consistency in formatting
I’ve updated the code.
Pull request overview
Copilot reviewed 16 out of 16 changed files in this pull request and generated no new comments.
Do we do the same for kustomize?
@camilamacedo86
Not yet on the kustomize side.
The standard config/network-policy/allow-metrics-traffic.yaml only allows the metrics port.
We're generating the extra webhook allow policy only in Helm for now (when webhooks exist).
I'll make it match Kustomize
Yes, NetworkPolicy should follow the ServiceMonitor fallback pattern. I updated the scaffolder to generate fallback NetworkPolicies when the kustomize output does not provide them, and regenerated the chart testdata so the samples now include the generated NetworkPolicy templates.
/ok-to-test
Hi @mattsu2020
Thank you for the nice work.
Could you please squash all commits in one commit?
Also, can you please rebase with master?
Beyond that, I think is missing we check
Hi @mattsu2020
> Thank you for the nice work. Could you please squash all commits in one commit? Also, can you please rebase with master?
> Beyond that, I think is missing we check
> a) docs, do we need update regards the NP
b) the help for the command in the cobra . We might need to update it
Added the missing documentation update.
@mattsu2020: The following test failed, say/retestto rerun all failed tests or/retest-requiredto rerun all mandatory failed tests:
> Test name Commit Details Required Rerun command
pull-kubebuilder-e2e-k8s-1-36-0 6d5a7f4 link true /test pull-kubebuilder-e2e-k8s-1-36-0
Full PR test history. Your PR dashboard. Please help us cut down on flakes by linking to an open issue when you hit one in your PR.
> Details
@camilamacedo86
~~Should we address the missing 1.36 support in this PR, or should it be handled in a separate PR?~~
I found the PR below, so I’ll wait for it to be addressed.
https://github.com/kubernetes-sigs/kubebuilder/pull/5674
Hi @mattsu2020
Regards /test pull-kubebuilder-e2e-k8s-1-36-0 do not worry about it.
It will not pass until we have a release from kind supporting 1.36. See: https://github.com/kubernetes-sigs/kubebuilder/pull/5674
We do not need to pass on this one to allow this one get merged. We can overwrite
We need a comment here ( This file should ONLY be scaffolded when the project HasWebhooks).
Something like
│ └── allow-webhook-traffic.yaml # When webhooks are found
When the kustomize output includes `NetworkPolicy` resources, the plugin converts them into chart templates and sets `networkPolicy.enable: true`. When no `NetworkPolicy` resources are present in the kustomize output, the plugin generates default templates for metrics traffic, and also for webhook traffic when webhooks are detected in the provided kustomize input files.
I think this test is not required
But we need ensure that:
a) If has webhooks then we have NP for webhooks scaffolded
b) If has not webhooks then we have only for metrics
c) if we found NPs in the kustomize all of them indeed others defined will end up in the np folder under the helm charts
d) If we scaffolded the default ones and then we found in the kustomize file new NPS all should go to the np dir as well.
Any NP should go to np file dir so it seems right
See from docs and cobra commands so, I think we will need to add NP here as well.
Would that really make sense ? if so we need to add here and also update the info in the COBRA help for this command. ServiceMonitors should follow the same configuration as well, but align fix there is out of scope.
So, the first question is should we preserve the end users customizations on this one?
If not we can remove the force
Never overwrites Chart.yaml; preserves values.yaml, NOTES.txt, _helpers.tpl, .helmignore, and test-chart.yml unless you use --force
It seems solved right?
👍 Great
Hi @mattsu2020
Really good work 🎉
I just add small few comments as my last round of reviews.
Amazing work really !!!
The fallback NetworkPolicy templates are added based on HasMetricsNetworkPolicy/name-suffix detection rather than on the presence of any NetworkPolicy resources. If a project provides custom NetworkPolicies (or uses different names), HasNetworkPolicy will still default networkPolicy.enable to true, and this block may silently add the default restrictive policy on top—changing default behavior and potentially breaking ingress expectations. Consider only scaffolding fallback policies when no NetworkPolicy resources are present at all (e.g., !extraction.Features.HasNetworkPolicy), or make the fallback decision based on stronger detection than filename suffixes.
Pull request overview
Copilot reviewed 18 out of 29 changed files in this pull request and generated 4 comments.
/override pull-kubebuilder-e2e-k8s-1-36-0
@camilamacedo86: Overrode contexts on behalf of camilamacedo86: pull-kubebuilder-e2e-k8s-1-36-0
<details>
In response to this:
>/override pull-kubebuilder-e2e-k8s-1-36-0
Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
</details>
/override pull-kubebuilder-e2e-k8s-1-36-0
@camilamacedo86: Overrode contexts on behalf of camilamacedo86: pull-kubebuilder-e2e-k8s-1-36-0
<details>
In response to this:
>/override pull-kubebuilder-e2e-k8s-1-36-0
>
Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
</details>
[APPROVALNOTIFIER] This PR is APPROVED
This pull-request has been approved by: <a href="https://github.com/kubernetes-sigs/kubebuilder/pull/5708#pullrequestreview-4364040602" title="Approved">camilamacedo86</a>, <a href="https://github.com/kubernetes-sigs/kubebuilder/pull/5708#" title="Author self-approved">mattsu2020</a>
The full list of commands accepted by this bot can be found here.
The pull request process is described here
<details >
Needs approval from an approver in each of these files:
Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment
</details>
<!-- META={"approvers":[]} -->
It seems great 🎉 Well done
Thank you.
It was a great learning experience for me regarding Kubebuilder.
/override pull-kubebuilder-e2e-k8s-1-36-0
@camilamacedo86: Overrode contexts on behalf of camilamacedo86: pull-kubebuilder-e2e-k8s-1-36-0
<details>
In response to this:
>/override pull-kubebuilder-e2e-k8s-1-36-0
Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
</details>
Thank you again for the review and approval.
could you please add /lgtm
/lgtm
mattsu2020
Summary
Fixes #5471
The helm/v2-alpha plugin has inconsistent handling between
prometheusandnetwork-policyoptions. Prometheus always emitsprometheus.enable: falsein values.yaml with conditional template guards, but NetworkPolicy resources get no values.yaml entry and no conditional wrapper — making it impossible to toggle NetworkPolicy via Helm values alone.This PR adds NetworkPolicy support following the same pattern as prometheus and certManager:
kind: NetworkPolicywithapiVersion: networking.k8s.io/v1HasNetworkPolicyflag set when NetworkPolicy resources exist"network-policy"template directory{{- if .Values.networkPolicy.enable }}networkPolicy.enable— defaults totruewhen NetworkPolicy resources are present in kustomize input,falseotherwise (matching the certManager pattern)Changes
| File | Change |
|---|---|
|
consts.go| AddKindNetworkPolicy+APIVersionNetworkingconstants ||
parser.go| AddNetworkPoliciesfield + switch case ||
extractor.go| AddNetworkPoliciestoResourceSet||
features.go| AddHasNetworkPolicyflag + detection ||
chart_scaffolder.go| MapNetworkPoliciesto extractor ||
categorizer.go| Add"network-policy"group ||
conditionals.go| Add conditional wrapper with apiVersion check ||
values.go| Add dynamicnetworkPolicy.enablesection ||
generator.go| Add"network-policy"toshouldSplitFiles|Test plan
networkPolicy:\n enable: truewhen detectednetworkPolicy:\n enable: falsewhen absentkubebuilder init --plugins=helm/v2-alpha+kubebuilder edit(requires integration tag)