Skip to content

feat: Add ability to patch dataplane Service, Deployment, and DaemonSet in NginxProxy #3630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

ciarams87
Copy link
Contributor

Proposed changes

Problem: There are many Deployment and Service fields that can be customized, and having to expose all of them in the NginxProxy resource is tedious and unnecessary for uncommonly used fields.

Solution: Add a way to submit custom patches to unblock users who need to set fields that are not yet exposed in the NginxProxy CRD. This commit adds support for patching the Service, Deployment, and DaemonSet resources using StrategicMerge (default kubernetes patch strategy), Merge (used when the intelligent strategic merge behaviour is not desired, e.g. to replace an array instead of merging them), and JSONPatch (used when precise modifications are needed, such as adding elements to specific array indices or performing conditional operations based on existing values).

Testing: Unit testing, and manual testing all the variations. Example NginxProxy:

apiVersion: gateway.nginx.org/v1alpha2
kind: NginxProxy
metadata:
  name: custom-proxy
spec:
  kubernetes:
    # Service patches - demonstrates all three patch types
    service:
      patches:
        # Strategic merge patch - adds custom labels and annotations
        - type: StrategicMerge
          value:
            metadata:
              labels:
                custom-label: "service-patched"
                environment: "test"
              annotations:
                custom-annotation: "applied-via-patch"
        # Merge patch - modifies spec fields
        - type: Merge
          value:
            spec:
              sessionAffinity: "ClientIP"
        # JSON patch - adds a specific annotation
        - type: JSONPatch
          value:
            - op: add
              path: "/metadata/annotations/patched-by"
              value: "json-patch"
            - op: add
              path: "/spec/loadBalancerSourceRanges"
              value: ["10.0.0.0/8", "192.168.0.0/16"]

    # Deployment patches - for when nginx.kind is "deployment"
    deployment:
      patches:
        # Strategic merge patch - adds deployment-specific labels
        - type: StrategicMerge
          value:
            metadata:
              labels:
                deployment-type: "nginx-proxy"
                patched: "true"
            spec:
              template:
                metadata:
                  labels:
                    pod-patched: "true"
        # JSON patch - modifies strategy and adds env var
        - type: JSONPatch
          value:
            - op: add
              path: "/spec/strategy"
              value:
                type: "RollingUpdate"
                rollingUpdate:
                  maxUnavailable: 1
                  maxSurge: 1
            - op: add
              path: "/spec/template/spec/containers/0/env"
              value:
                - name: "PATCHED_BY"
                  value: "json-patch"
                - name: "DEPLOYMENT_MODE"
                  value: "patched"

Note 1: We don't have the ability to perform validation on patches. Errors in Patches will be logged in the control plane, but will not be reported in the status of the NginxProxy. Additionally, the resources will be created regardless - I don't believe we should fail the resource creation because of patch errors. It will be on the user to ensure patches have been applied correctly (this will be documented in the data plane configuration doc)

Note 2: Uses gopkg.in/evanphx/json-patch.v4 instead of the latest v5 to match Kubernetes ecosystem libraries and ensure consistent RFC 6902 compliance with kubectl. See this issue for a similar example

Closes #3568

Checklist

Before creating a PR, run through this checklist and mark each as complete.

  • I have read the CONTRIBUTING doc
  • I have added tests that prove my fix is effective or that my feature works
  • I have checked that all unit tests pass after adding my changes
  • I have updated necessary documentation
  • I have rebased my branch onto main
  • I will ensure my PR is targeting the main branch and pulling from my branch from my own fork

Release notes

If this PR introduces a change that affects users and needs to be mentioned in the release notes,
please add a brief note that summarizes the change.

Added the ability to patch the dataplane Service, Deployment, and DaemonSet resources through NginxProxy

@ciarams87 ciarams87 requested a review from a team as a code owner July 16, 2025 16:02
@github-actions github-actions bot added enhancement New feature or request dependencies Pull requests that update a dependency file labels Jul 16, 2025
Copy link

codecov bot commented Jul 16, 2025

Codecov Report

Attention: Patch coverage is 84.21053% with 15 lines in your changes missing coverage. Please review.

Project coverage is 86.85%. Comparing base (b5cf4be) to head (da6ed02).

Files with missing lines Patch % Lines
internal/controller/provisioner/objects.go 84.21% 10 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3630      +/-   ##
==========================================
- Coverage   86.87%   86.85%   -0.03%     
==========================================
  Files         127      127              
  Lines       15287    15354      +67     
  Branches       62       62              
==========================================
+ Hits        13281    13335      +54     
- Misses       1851     1860       +9     
- Partials      155      159       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

// For JSONPatch patches, this should be a JSON array of patch operations.
//
// +kubebuilder:validation:XPreserveUnknownFields
Value *apiextv1.JSON `json:"value"`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this field be marked as optional?

Comment on lines +182 to +186
if len(errs) > 0 {
return objects, errors.Join(errs...)
}

return objects, nil
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you could just do return objects, errors.Join(errs...). If errs is empty, it should return nil.


const (
// PatchTypeStrategicMerge uses strategic merge patch.
PatchTypeStrategicMerge PatchType = "StrategicMerge"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does k8s define these types at all? If so, it'd be nice to alias our types to theirs, instead of using the string literal.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@@ -537,6 +567,15 @@ func (p *NginxProvisioner) buildNginxDeployment(
Template: podTemplateSpec,
},
}

// Apply DaemonSet patches
if nProxyCfg.Kubernetes.DaemonSet != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this if statement not needed since the check is already above?

Comment on lines +601 to +605
if nProxyCfg != nil && nProxyCfg.Kubernetes != nil && nProxyCfg.Kubernetes.Deployment != nil {
if err := applyPatches(deployment, nProxyCfg.Kubernetes.Deployment.Patches); err != nil {
return deployment, fmt.Errorf("failed to apply deployment patches: %w", err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can we combine the above line

if nProxyCfg != nil && nProxyCfg.Kubernetes != nil && nProxyCfg.Kubernetes.Deployment != nil {
		deploymentCfg = *nProxyCfg.Kubernetes.Deployment
	}

into this statement?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if its possible, can you add another test case where a patch later on in the array overrides a field set in a previous patch?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dependencies Pull requests that update a dependency file enhancement New feature or request release-notes
Projects
Status: 🆕 New
Development

Successfully merging this pull request may close these issues.

Allow users to submit custom patches to nginx deployment/service specs
3 participants