Skip to content

Commit 0920fb0

Browse files
committed
fix: pre-create namespace if doesn't exist in management cluster
1 parent bc47736 commit 0920fb0

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

pkg/handlers/generic/lifecycle/clusterautoscaler/strategy_crs.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"github.com/spf13/pflag"
1212
corev1 "k8s.io/api/core/v1"
1313
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
14+
"sigs.k8s.io/cluster-api/controllers/remote"
1415
runtimehooksv1 "sigs.k8s.io/cluster-api/exp/runtime/hooks/api/v1alpha1"
1516
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
1617

@@ -114,7 +115,23 @@ func (s crsStrategy) apply(
114115
targetCluster = cluster
115116
}
116117

117-
if err := utils.EnsureCRSForClusterFromConfigMaps(ctx, cm.Name, s.client, targetCluster, cm); err != nil {
118+
// In the case when existingManagementCluster is nil, i.e. when s.client points to a bootstrap cluster,
119+
// it is possible that the namespace where the cluster will be moved to, and where the cluster-autoscaler resources
120+
// will be created, does not exist yet.
121+
// In that case, we need to create the namespace in the target cluster.
122+
clusterKey := ctrlclient.ObjectKeyFromObject(targetCluster)
123+
remoteClient, err := remote.NewClusterClient(ctx, "", s.client, clusterKey)
124+
if err != nil {
125+
return fmt.Errorf("error creating remote cluster client: %w", err)
126+
}
127+
if err = utils.EnsureNamespace(ctx, remoteClient, cluster.Namespace); err != nil {
128+
return fmt.Errorf(
129+
"failed to create Namespace in remote cluster: %w",
130+
err,
131+
)
132+
}
133+
134+
if err = utils.EnsureCRSForClusterFromConfigMaps(ctx, cm.Name, s.client, targetCluster, cm); err != nil {
118135
return fmt.Errorf(
119136
"failed to apply cluster-autoscaler installation ClusterResourceSet: %w",
120137
err,

pkg/handlers/generic/lifecycle/utils/utils.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,28 @@ func EnsureCRSForClusterFromConfigMaps(
6161

6262
return nil
6363
}
64+
65+
// EnsureNamespace will create the namespece if it does not exist.
66+
func EnsureNamespace(ctx context.Context, c ctrlclient.Client, name string) error {
67+
ns := &corev1.Namespace{
68+
TypeMeta: metav1.TypeMeta{
69+
APIVersion: corev1.SchemeGroupVersion.String(),
70+
Kind: "Namespace",
71+
},
72+
ObjectMeta: metav1.ObjectMeta{
73+
Name: name,
74+
},
75+
}
76+
77+
// check if namespace exists and return early if it does
78+
if err := c.Get(ctx, ctrlclient.ObjectKeyFromObject(ns), ns); err == nil {
79+
return nil
80+
}
81+
82+
err := client.ServerSideApply(ctx, c, ns)
83+
if err != nil {
84+
return fmt.Errorf("failed to server side apply %w", err)
85+
}
86+
87+
return nil
88+
}

0 commit comments

Comments
 (0)