diff --git a/api/v1alpha3/machinedeployment_webhook.go b/api/v1alpha3/machinedeployment_webhook.go index 5ce67f553eb7..88fa1ef30e98 100644 --- a/api/v1alpha3/machinedeployment_webhook.go +++ b/api/v1alpha3/machinedeployment_webhook.go @@ -144,4 +144,7 @@ func PopulateDefaultsMachineDeployment(d *MachineDeployment) { d.Spec.Selector.MatchLabels[MachineDeploymentLabelName] = d.Name d.Spec.Template.Labels[MachineDeploymentLabelName] = d.Name } + // Make sure selector and template to be in the same cluster. + d.Spec.Selector.MatchLabels[ClusterLabelName] = d.Spec.ClusterName + d.Spec.Template.Labels[ClusterLabelName] = d.Spec.ClusterName } diff --git a/api/v1alpha3/machinedeployment_webhook_test.go b/api/v1alpha3/machinedeployment_webhook_test.go index efb475e7eafe..1d7ac73ab2c9 100644 --- a/api/v1alpha3/machinedeployment_webhook_test.go +++ b/api/v1alpha3/machinedeployment_webhook_test.go @@ -111,3 +111,21 @@ func TestMachineDeploymentValidation(t *testing.T) { }) } } + +func TestMachineDeploymentWithSpec(t *testing.T) { + g := NewWithT(t) + md := MachineDeployment{ + Spec: MachineDeploymentSpec{ + ClusterName: "test-cluster", + Template: MachineTemplateSpec{ + Spec: MachineSpec{ + ClusterName: "test-cluster", + }, + }, + }, + } + + md.Default() + g.Expect(md.Spec.Selector.MatchLabels).To(HaveKeyWithValue(ClusterLabelName, "test-cluster")) + g.Expect(md.Spec.Template.Labels).To(HaveKeyWithValue(ClusterLabelName, "test-cluster")) +} diff --git a/controllers/machinedeployment_controller.go b/controllers/machinedeployment_controller.go index d318aa331768..7fe99f7ae52e 100644 --- a/controllers/machinedeployment_controller.go +++ b/controllers/machinedeployment_controller.go @@ -148,10 +148,6 @@ func (r *MachineDeploymentReconciler) reconcile(_ context.Context, cluster *clus d.Labels[clusterv1.ClusterLabelName] = d.Spec.ClusterName - // Make sure selector and template to be in the same cluster. - d.Spec.Selector.MatchLabels[clusterv1.ClusterLabelName] = d.Spec.ClusterName - d.Spec.Template.Labels[clusterv1.ClusterLabelName] = d.Spec.ClusterName - if r.shouldAdopt(d) { d.OwnerReferences = util.EnsureOwnerRef(d.OwnerReferences, metav1.OwnerReference{ APIVersion: clusterv1.GroupVersion.String(),