Skip to content
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

access to client in mutating webhook #1216

Closed
ryandawsonuk opened this issue Nov 22, 2019 · 18 comments
Closed

access to client in mutating webhook #1216

ryandawsonuk opened this issue Nov 22, 2019 · 18 comments
Labels
kind/support Categorizes issue or PR as a support question. lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed.

Comments

@ryandawsonuk
Copy link

ryandawsonuk commented Nov 22, 2019

I'd like to use the manager's client to reference a configmap when validating my custom resource. But I can't see a way to pass the manager's client through to the webhook code (the Defaulter) when using the NewWebhookManagedBy form:

func (r *FirstMate) SetupWebhookWithManager(mgr ctrl.Manager) error {
	return ctrl.NewWebhookManagedBy(mgr).
		For(r).
		Complete()
}

A related question put me on to the .Register form which I think would let me pass down the manager's client to the code that would be triggered by the webhook.

I might end up loading the configmap as an env var (I've read you can do this though can't find an example). But I'm wondering is it intended that the SetupWebhookWithManager doesn't let you use a client inside the webhook code? Or perhaps I'm missing something?

@ryandawsonuk ryandawsonuk added the kind/support Categorizes issue or PR as a support question. label Nov 22, 2019
@ryandawsonuk ryandawsonuk reopened this Nov 28, 2019
@pires
Copy link
Contributor

pires commented Nov 28, 2019

If that's what you really want, why not change your FirstMate and add a client Client attribute to its struct, so that then you can...

func (r *FirstMate) SetupWebhookWithManager(mgr ctrl.Manager) error {
    c := ctrl.NewWebhookManagedBy(mgr).
        For(r).
        Build()

    c.client = mgr.GetClient()
    r.controller = c

    return nil
}

@ryandawsonuk
Copy link
Author

Wouldn't the client then be an attribute on the custom resource (FirstMate in this example case and so be treated as part of the CRD and included in the generated CR definition?

@pires
Copy link
Contributor

pires commented Nov 28, 2019

According to the snippet of code you pasted, FirstMate is the name of your controller/reconciler. oh wait, you're right. Let me read the linked code and I'll come back to you.

@pires
Copy link
Contributor

pires commented Nov 28, 2019

Maybe something like...

var (
    firstmatelog = logf.Log.WithName("firstmate-resource")
    client Client
)

func (r *FirstMate) SetupWebhookWithManager(mgr ctrl.Manager) error {
    client = mgr.getClient()

    return ctrl.NewWebhookManagedBy(mgr).
        For(r).
        Build()
}

var _ webhook.Defaulter = &FirstMate{}

// Default implements webhook.Defaulter so a webhook will be registered for the type
func (r *FirstMate) Default() {
    firstmatelog.Info("default", "name", r.Name)

    // TODO use client to read other resources
    client.Get(...)

    // TODO(user): fill in your defaulting logic.
}

@pires
Copy link
Contributor

pires commented Nov 28, 2019

Do have in mind the client will need access to the scheme(s) of the type(s) you'll be interacting with.

@ryandawsonuk
Copy link
Author

@DirectXMan12
Copy link
Contributor

If you need to use a client, I'd reccomend using the lower-level webhook machinery in pkg/admission/webhook.

@DirectXMan12
Copy link
Contributor

we really need an FAQ item on this

@mazzy89
Copy link

mazzy89 commented Jan 25, 2020

kubernetes-sigs/controller-runtime#780 - I get an error following the example.

@mazzy89
Copy link

mazzy89 commented Jan 26, 2020

solved this. example in here kubernetes-sigs/controller-runtime#780 (comment)

@fejta-bot
Copy link

Issues go stale after 90d of inactivity.
Mark the issue as fresh with /remove-lifecycle stale.
Stale issues rot after an additional 30d of inactivity and eventually close.

If this issue is safe to close now please do so with /close.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle stale

@k8s-ci-robot k8s-ci-robot added the lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. label Apr 25, 2020
@fejta-bot
Copy link

Stale issues rot after 30d of inactivity.
Mark the issue as fresh with /remove-lifecycle rotten.
Rotten issues close after an additional 30d of inactivity.

If this issue is safe to close now please do so with /close.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/lifecycle rotten

@k8s-ci-robot k8s-ci-robot added lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed. and removed lifecycle/stale Denotes an issue or PR has remained open with no activity and has become stale. labels May 25, 2020
@fejta-bot
Copy link

Rotten issues close after 30d of inactivity.
Reopen the issue with /reopen.
Mark the issue as fresh with /remove-lifecycle rotten.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/close

@k8s-ci-robot
Copy link
Contributor

@fejta-bot: Closing this issue.

In response to this:

Rotten issues close after 30d of inactivity.
Reopen the issue with /reopen.
Mark the issue as fresh with /remove-lifecycle rotten.

Send feedback to sig-testing, kubernetes/test-infra and/or fejta.
/close

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/test-infra repository.

@m-yosefpor
Copy link

What is the best way of doing this in 2021?

Should we do it with @pires solution or as @DirectXMan12 said, using lower level webhook? or is there any better alternative right now?

@strideynet
Copy link

What is the best way of doing this in 2021?

Should we do it with @pires solution or as @DirectXMan12 said, using lower level webhook? or is there any better alternative right now?

I would suggest using the lower level webhooks ( see https://github.com/kubernetes-sigs/controller-runtime/blob/master/examples/builtins/mutatingwebhook.go )

@calebschoepp
Copy link

I recently ran into this issue. Here's how I solved it (note replace foo with your CR name):

main.go

...
	if os.Getenv("ENABLE_WEBHOOKS") != "false" {
		if err = webhook.SetupFooWebhookWithManager(mgr); err != nil {
			setupLog.Error(err, "unable to create webhook", "webhook", "Foo")
			os.Exit(1)
		}
	}
...

internal/webhook/admission.go

package webhook

import (
	foov1 "github.com/company/foo/api/v1"
	ctrl "sigs.k8s.io/controller-runtime"
)

func SetupFooWebhookWithManager(mgr ctrl.Manager) error {
	return ctrl.NewWebhookManagedBy(mgr).
		For(&foov1.Foo{}).
		WithDefaulter(&Foo{Client: mgr.GetClient()}).
		WithValidator(&FooValidator{Client: mgr.GetClient()}).
		Complete()
}

internal/webhook/validating.go

package webhook

import (
	"context"

	foov1 "github.com/company/foo/api/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/validation/field"
	"sigs.k8s.io/controller-runtime/pkg/client"

	"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

//+kubebuilder:webhook:path=/validate-foo-company-com-v1-foo,mutating=false,failurePolicy=fail,sideEffects=None,groups=foo.company.com,resources=foos,verbs=create;update,versions=v1,name=vfoo.kb.io,admissionReviewVersions=v1

// FooValidator validates Foos
type FooValidator struct {
	Client client.Client
}

// ValidateCreate implements webhook.Validator
func (v *FooValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
	foo := obj.(*foov1.Foo)
	return nil, v.validateFoo(foo)
}

// ValidateUpdate implements webhook.Validator
func (v *FooValidator) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) {
	foo := newObj.(*foov1.Foo)
	return nil, v.validateFoo(foo)
}

// ValidateDelete implements webhook.Validator
func (v *FooValidator) ValidateDelete(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
	return nil, nil
}

func (v *FooValidator) validateFoo(foo *foov1.Foo) error {
	// TODO: Your validation logic
	return nil
}

internal/defaulting.go

package webhook

import (
	"context"

	foov1 "github.com/company/foo/api/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

//+kubebuilder:webhook:path=/mutate-foo-company-com-v1-foo,mutating=true,failurePolicy=fail,sideEffects=None,groups=foo.company.com,resources=foo,verbs=create;update,versions=v1,name=mfoo.kb.io,admissionReviewVersions=v1

// FooDefaulter mutates Foos
type FooDefaulter struct {
	Client client.Client
}

// Default implements webhook.Defaulter
func (d *FooDefaulter) Default(ctx context.Context, obj runtime.Object) error {
	foo := obj.(*foov1.Foo)

	// TODO: Your default logic

	return nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind/support Categorizes issue or PR as a support question. lifecycle/rotten Denotes an issue or PR that has aged beyond stale and will be auto-closed.
Projects
None yet
Development

No branches or pull requests

9 participants