Skip to content

Commit a0fcbf9

Browse files
committed
Shorten name of network policies
If the combination of application and target instance name is too long, it would previously fail to create a network policy. Now we shorten the name in these cases. Deletion has always been based on label selector and isn't affected. This also means the change is backwards compatible.
1 parent 793bbe0 commit a0fcbf9

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

internal/pkg/netpol/netpol.go

+15-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package netpol
33
import (
44
"context"
55
"fmt"
6+
"github.com/nais/liberator/pkg/namegen"
7+
"k8s.io/apimachinery/pkg/util/validation"
68
"os"
79

810
"github.com/nais/cloudsql-migrator/internal/pkg/common_main"
@@ -20,9 +22,20 @@ func CreateNetworkPolicy(ctx context.Context, cfg *config.Config, source *resolv
2022
return nil
2123
}
2224

25+
var err error
26+
27+
name := fmt.Sprintf("migration-%s-%s", cfg.ApplicationName, target.Name)
28+
maxlen := validation.DNS1123LabelMaxLength
29+
if len(name) > maxlen {
30+
name, err = namegen.ShortName(name, maxlen)
31+
if err != nil {
32+
return fmt.Errorf("BUG: generating netpol name: %w", err)
33+
}
34+
}
35+
2336
netpol := &v1.NetworkPolicy{
2437
ObjectMeta: metav1.ObjectMeta{
25-
Name: fmt.Sprintf("migration-%s-%s", cfg.ApplicationName, target.Name),
38+
Name: name,
2639
Namespace: cfg.Namespace,
2740
Labels: map[string]string{
2841
"app": cfg.ApplicationName,
@@ -52,7 +65,7 @@ func CreateNetworkPolicy(ctx context.Context, cfg *config.Config, source *resolv
5265
}
5366

5467
mgr.Logger.Info("creating network policy", "name", netpol.Name)
55-
_, err := mgr.K8sClient.NetworkingV1().NetworkPolicies(cfg.Namespace).Create(ctx, netpol, metav1.CreateOptions{})
68+
_, err = mgr.K8sClient.NetworkingV1().NetworkPolicies(cfg.Namespace).Create(ctx, netpol, metav1.CreateOptions{})
5669
if err != nil {
5770
if k8s_errors.IsAlreadyExists(err) {
5871
mgr.Logger.Info("network policy already exists, updating", "name", netpol.Name)

0 commit comments

Comments
 (0)