Skip to content

Commit 72c774d

Browse files
committed
Introduce spec.ClusterName for ProviderServiceAccount
Introduce spec.ClusterName for ProviderServiceAccount, also add validation webhook for it. Signed-off-by: Gong Zhang <[email protected]>
1 parent 3559ab2 commit 72c774d

10 files changed

+324
-13
lines changed

apis/vmware/v1beta1/providerserviceaccount_types.go

+6
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,13 @@ import (
2424

2525
// ProviderServiceAccountSpec defines the desired state of ProviderServiceAccount.
2626
type ProviderServiceAccountSpec struct {
27+
// ClusterName is the name of the Cluster this object belongs to.
28+
// +optional
29+
ClusterName *string `json:"clusterName"`
30+
31+
// Deprecated: Ref will be removed in a future release.
2732
// Ref specifies the reference to the VSphereCluster for which the ProviderServiceAccount needs to be realized.
33+
// +optional
2834
Ref *corev1.ObjectReference `json:"ref"`
2935

3036
// Rules specifies the privileges that need to be granted to the service account.

apis/vmware/v1beta1/zz_generated.deepcopy.go

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

config/supervisor/crd/vmware.infrastructure.cluster.x-k8s.io_providerserviceaccounts.yaml

+7-3
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,14 @@ spec:
5050
spec:
5151
description: ProviderServiceAccountSpec defines the desired state of ProviderServiceAccount.
5252
properties:
53+
clusterName:
54+
description: ClusterName is the name of the Cluster this object belongs
55+
to.
56+
type: string
5357
ref:
54-
description: Ref specifies the reference to the VSphereCluster for
55-
which the ProviderServiceAccount needs to be realized.
58+
description: 'Deprecated: Ref will be removed in a future release.
59+
Ref specifies the reference to the VSphereCluster for which the
60+
ProviderServiceAccount needs to be realized.'
5661
properties:
5762
apiVersion:
5863
description: API version of the referent.
@@ -149,7 +154,6 @@ spec:
149154
cluster that contains the generated service account token.
150155
type: string
151156
required:
152-
- ref
153157
- rules
154158
- targetNamespace
155159
- targetSecretName

config/webhook/manifests.yaml

+42
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,27 @@ kind: MutatingWebhookConfiguration
44
metadata:
55
name: mutating-webhook-configuration
66
webhooks:
7+
- admissionReviewVersions:
8+
- v1beta1
9+
clientConfig:
10+
service:
11+
name: webhook-service
12+
namespace: system
13+
path: /mutate-vmware-infrastructure-cluster-x-k8s-io-v1beta1-providerserviceaccount
14+
failurePolicy: Fail
15+
matchPolicy: Equivalent
16+
name: default.providerserviceaccount.vmware.infrastructure.cluster.x-k8s.io
17+
rules:
18+
- apiGroups:
19+
- vmware.infrastructure.cluster.x-k8s.io
20+
apiVersions:
21+
- v1beta1
22+
operations:
23+
- CREATE
24+
- UPDATE
25+
resources:
26+
- providerserviceaccounts
27+
sideEffects: None
728
- admissionReviewVersions:
829
- v1beta1
930
clientConfig:
@@ -94,6 +115,27 @@ kind: ValidatingWebhookConfiguration
94115
metadata:
95116
name: validating-webhook-configuration
96117
webhooks:
118+
- admissionReviewVersions:
119+
- v1beta1
120+
clientConfig:
121+
service:
122+
name: webhook-service
123+
namespace: system
124+
path: /validate-vmware-infrastructure-cluster-x-k8s-io-v1beta1-providerserviceaccount
125+
failurePolicy: Fail
126+
matchPolicy: Equivalent
127+
name: validation.providerserviceaccount.vmware.infrastructure.x-k8s.io
128+
rules:
129+
- apiGroups:
130+
- vmware.infrastructure.cluster.x-k8s.io
131+
apiVersions:
132+
- v1beta1
133+
operations:
134+
- CREATE
135+
- UPDATE
136+
resources:
137+
- providerserviceaccounts
138+
sideEffects: None
97139
- admissionReviewVersions:
98140
- v1beta1
99141
clientConfig:

controllers/serviceaccount_controller.go

+26-9
Original file line numberDiff line numberDiff line change
@@ -582,9 +582,17 @@ func (r *ServiceAccountReconciler) getProviderServiceAccounts(ctx context.Contex
582582
if pSvcAccount.DeletionTimestamp != nil {
583583
continue
584584
}
585-
ref := pSvcAccount.Spec.Ref
586-
if ref != nil && ref.Name == clusterCtx.VSphereCluster.Name {
587-
pSvcAccounts = append(pSvcAccounts, pSvcAccount)
585+
// take ClusterName as higher precedence temporally before Ref was deprecated.
586+
if pSvcAccount.Spec.ClusterName != nil && *pSvcAccount.Spec.ClusterName != "" {
587+
clusterName := *pSvcAccount.Spec.ClusterName
588+
if clusterName == clusterCtx.VSphereCluster.Name {
589+
pSvcAccounts = append(pSvcAccounts, pSvcAccount)
590+
}
591+
} else {
592+
ref := pSvcAccount.Spec.Ref //nolint:staticcheck
593+
if ref != nil && ref.Name == clusterCtx.VSphereCluster.Name {
594+
pSvcAccounts = append(pSvcAccounts, pSvcAccount)
595+
}
588596
}
589597
}
590598
return pSvcAccounts, nil
@@ -678,11 +686,20 @@ func (r *ServiceAccountReconciler) providerServiceAccountToVSphereCluster(_ cont
678686
}
679687

680688
func toVSphereClusterRequest(providerServiceAccount *vmwarev1.ProviderServiceAccount) []reconcile.Request {
681-
vsphereClusterRef := providerServiceAccount.Spec.Ref
682-
if vsphereClusterRef == nil || vsphereClusterRef.Name == "" {
683-
return nil
684-
}
685-
return []reconcile.Request{
686-
{NamespacedName: client.ObjectKey{Namespace: providerServiceAccount.Namespace, Name: vsphereClusterRef.Name}},
689+
// take ClusterName as higher precedence temporally before Ref was deprecated.
690+
if providerServiceAccount.Spec.ClusterName != nil && *providerServiceAccount.Spec.ClusterName != "" {
691+
clusterName := *providerServiceAccount.Spec.ClusterName
692+
return []reconcile.Request{
693+
{NamespacedName: client.ObjectKey{Namespace: providerServiceAccount.Namespace, Name: clusterName}},
694+
}
695+
} else if providerServiceAccount.Spec.Ref != nil { //nolint:staticcheck
696+
vsphereClusterRef := providerServiceAccount.Spec.Ref //nolint:staticcheck
697+
if vsphereClusterRef.Name != "" {
698+
return []reconcile.Request{
699+
{NamespacedName: client.ObjectKey{Namespace: providerServiceAccount.Namespace, Name: vsphereClusterRef.Name}},
700+
}
701+
}
687702
}
703+
704+
return nil
688705
}

controllers/serviceaccount_controller_suite_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ func getTestProviderServiceAccount(namespace string, vSphereCluster *vmwarev1.VS
221221
Controller: &truePointer,
222222
},
223223
}
224-
pSvcAccount.Spec.Ref = &corev1.ObjectReference{
224+
pSvcAccount.Spec.Ref = &corev1.ObjectReference{ //nolint:staticcheck
225225
Name: vSphereCluster.Name,
226226
}
227227
}

internal/test/helpers/envtest.go

+4
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ func NewTestEnvironment(ctx context.Context) *TestEnvironment {
179179
return err
180180
}
181181

182+
if err := (&webhooks.ProviderServiceAccountWebhook{}).SetupWebhookWithManager(mgr); err != nil {
183+
return err
184+
}
185+
182186
return (&webhooks.VSphereFailureDomainWebhook{}).SetupWebhookWithManager(mgr)
183187
}
184188

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/*
2+
Copyright 2024 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package webhooks
18+
19+
import (
20+
"context"
21+
"fmt"
22+
23+
apierrors "k8s.io/apimachinery/pkg/api/errors"
24+
"k8s.io/apimachinery/pkg/runtime"
25+
"k8s.io/apimachinery/pkg/util/validation/field"
26+
ctrl "sigs.k8s.io/controller-runtime"
27+
"sigs.k8s.io/controller-runtime/pkg/webhook"
28+
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
29+
30+
vmwarev1 "sigs.k8s.io/cluster-api-provider-vsphere/apis/vmware/v1beta1"
31+
)
32+
33+
// +kubebuilder:webhook:verbs=create;update,path=/validate-vmware-infrastructure-cluster-x-k8s-io-v1beta1-providerserviceaccount,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=vmware.infrastructure.cluster.x-k8s.io,resources=providerserviceaccounts,versions=v1beta1,name=validation.providerserviceaccount.vmware.infrastructure.x-k8s.io,sideEffects=None,admissionReviewVersions=v1beta1
34+
// +kubebuilder:webhook:verbs=create;update,path=/mutate-vmware-infrastructure-cluster-x-k8s-io-v1beta1-providerserviceaccount,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=vmware.infrastructure.cluster.x-k8s.io,resources=providerserviceaccounts,versions=v1beta1,name=default.providerserviceaccount.vmware.infrastructure.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1beta1
35+
36+
// ProviderServiceAccountWebhook implements a validation and defaulting webhook for ProviderServiceAccount.
37+
type ProviderServiceAccountWebhook struct{}
38+
39+
var _ webhook.CustomValidator = &ProviderServiceAccountWebhook{}
40+
var _ webhook.CustomDefaulter = &ProviderServiceAccountWebhook{}
41+
42+
func (webhook *ProviderServiceAccountWebhook) SetupWebhookWithManager(mgr ctrl.Manager) error {
43+
return ctrl.NewWebhookManagedBy(mgr).
44+
For(&vmwarev1.ProviderServiceAccount{}).
45+
WithValidator(webhook).
46+
WithDefaulter(webhook).
47+
Complete()
48+
}
49+
50+
// Default implements webhook.Defaulter so a webhook will be registered for the type.
51+
func (webhook *ProviderServiceAccountWebhook) Default(_ context.Context, _ runtime.Object) error {
52+
return nil
53+
}
54+
55+
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
56+
func (webhook *ProviderServiceAccountWebhook) ValidateCreate(_ context.Context, raw runtime.Object) (admission.Warnings, error) {
57+
var allErrs field.ErrorList
58+
59+
obj, ok := raw.(*vmwarev1.ProviderServiceAccount)
60+
if !ok {
61+
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a ProviderServiceAccount but got a %T", raw))
62+
}
63+
64+
spec := obj.Spec
65+
if spec.Ref == nil && (spec.ClusterName == nil || *spec.ClusterName == "") { //nolint:staticcheck
66+
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), "should specify Ref or ClusterName"))
67+
if spec.ClusterName != nil && *spec.ClusterName == "" {
68+
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "ClusterName"), "ClusterName should not be empty"))
69+
}
70+
}
71+
72+
return nil, aggregateObjErrors(obj.GroupVersionKind().GroupKind(), obj.Name, allErrs)
73+
}
74+
75+
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
76+
func (webhook *ProviderServiceAccountWebhook) ValidateUpdate(_ context.Context, _ runtime.Object, newRaw runtime.Object) (admission.Warnings, error) {
77+
var allErrs field.ErrorList
78+
79+
newTyped, ok := newRaw.(*vmwarev1.ProviderServiceAccount)
80+
if !ok {
81+
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a ProviderServiceAccount but got a %T", newRaw))
82+
}
83+
84+
spec := newTyped.Spec
85+
if spec.Ref == nil && (spec.ClusterName == nil || *spec.ClusterName == "") { //nolint:staticcheck
86+
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec"), "should specify Ref or ClusterName"))
87+
if spec.ClusterName != nil && *spec.ClusterName == "" {
88+
allErrs = append(allErrs, field.Forbidden(field.NewPath("spec", "ClusterName"), "ClusterName should not be empty"))
89+
}
90+
}
91+
92+
return nil, aggregateObjErrors(newTyped.GroupVersionKind().GroupKind(), newTyped.Name, allErrs)
93+
}
94+
95+
// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
96+
func (webhook *ProviderServiceAccountWebhook) ValidateDelete(_ context.Context, _ runtime.Object) (admission.Warnings, error) {
97+
return nil, nil
98+
}

0 commit comments

Comments
 (0)