Skip to content

Commit 440b9da

Browse files
authored
Merge pull request #1134 from fluxcd/kustomize-name-prefix-suffix
Implement name prefix/suffix transformers
2 parents fa5cebb + f21f65e commit 440b9da

File tree

8 files changed

+186
-7
lines changed

8 files changed

+186
-7
lines changed

api/v1/kustomization_types.go

+14
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,20 @@ type KustomizationSpec struct {
9999
// +optional
100100
HealthChecks []meta.NamespacedObjectKindReference `json:"healthChecks,omitempty"`
101101

102+
// NamePrefix will prefix the names of all managed resources.
103+
// +kubebuilder:validation:MinLength=1
104+
// +kubebuilder:validation:MaxLength=200
105+
// +kubebuilder:validation:Optional
106+
// +optional
107+
NamePrefix string `json:"namePrefix,omitempty" yaml:"namePrefix,omitempty"`
108+
109+
// NameSuffix will suffix the names of all managed resources.
110+
// +kubebuilder:validation:MinLength=1
111+
// +kubebuilder:validation:MaxLength=200
112+
// +kubebuilder:validation:Optional
113+
// +optional
114+
NameSuffix string `json:"nameSuffix,omitempty" yaml:"nameSuffix,omitempty"`
115+
102116
// Strategic merge and JSON patches, defined as inline YAML objects,
103117
// capable of targeting objects based on kind, label and annotation selectors.
104118
// +optional

config/crd/bases/kustomize.toolkit.fluxcd.io_kustomizations.yaml

+10
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,16 @@ spec:
221221
required:
222222
- secretRef
223223
type: object
224+
namePrefix:
225+
description: NamePrefix will prefix the names of all managed resources.
226+
maxLength: 200
227+
minLength: 1
228+
type: string
229+
nameSuffix:
230+
description: NameSuffix will suffix the names of all managed resources.
231+
maxLength: 200
232+
minLength: 1
233+
type: string
224234
patches:
225235
description: |-
226236
Strategic merge and JSON patches, defined as inline YAML objects,

docs/api/v1/kustomize.md

+48
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,30 @@ bool
222222
</tr>
223223
<tr>
224224
<td>
225+
<code>namePrefix</code><br>
226+
<em>
227+
string
228+
</em>
229+
</td>
230+
<td>
231+
<em>(Optional)</em>
232+
<p>NamePrefix will prefix the names of all managed resources.</p>
233+
</td>
234+
</tr>
235+
<tr>
236+
<td>
237+
<code>nameSuffix</code><br>
238+
<em>
239+
string
240+
</em>
241+
</td>
242+
<td>
243+
<em>(Optional)</em>
244+
<p>NameSuffix will suffix the names of all managed resources.</p>
245+
</td>
246+
</tr>
247+
<tr>
248+
<td>
225249
<code>patches</code><br>
226250
<em>
227251
<a href="https://godoc.org/github.com/fluxcd/pkg/apis/kustomize#Patch">
@@ -706,6 +730,30 @@ bool
706730
</tr>
707731
<tr>
708732
<td>
733+
<code>namePrefix</code><br>
734+
<em>
735+
string
736+
</em>
737+
</td>
738+
<td>
739+
<em>(Optional)</em>
740+
<p>NamePrefix will prefix the names of all managed resources.</p>
741+
</td>
742+
</tr>
743+
<tr>
744+
<td>
745+
<code>nameSuffix</code><br>
746+
<em>
747+
string
748+
</em>
749+
</td>
750+
<td>
751+
<em>(Optional)</em>
752+
<p>NameSuffix will suffix the names of all managed resources.</p>
753+
</td>
754+
</tr>
755+
<tr>
756+
<td>
709757
<code>patches</code><br>
710758
<em>
711759
<a href="https://godoc.org/github.com/fluxcd/pkg/apis/kustomize#Patch">

docs/spec/v1/kustomizations.md

+16
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,22 @@ should be applied to all the Kustomization's resources. It has two optional fiel
401401
on an object. Any existing annotation will be overridden if it matches with a key
402402
in this map.
403403

404+
### Name Prefix and Suffix
405+
406+
`.spec.namePrefix` and `.spec.nameSuffix` are optional fields used to specify a prefix and suffix
407+
to be added to the names of all the resources in the Kustomization.
408+
409+
```yaml
410+
apiVersion: kustomize.toolkit.fluxcd.io/v1
411+
kind: Kustomization
412+
metadata:
413+
name: app
414+
spec:
415+
# ...omitted for brevity
416+
namePrefix: "prefix-"
417+
nameSuffix: "-suffix"
418+
```
419+
404420
### Patches
405421

406422
`.spec.patches` is an optional list used to specify [Kustomize `patches`](https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/patches/)

go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ require (
2323
github.com/fluxcd/pkg/apis/kustomize v1.4.0
2424
github.com/fluxcd/pkg/apis/meta v1.4.0
2525
github.com/fluxcd/pkg/http/fetch v0.10.0
26-
github.com/fluxcd/pkg/kustomize v1.9.0
26+
github.com/fluxcd/pkg/kustomize v1.10.0
2727
github.com/fluxcd/pkg/runtime v0.46.0
2828
github.com/fluxcd/pkg/ssa v0.38.0
2929
github.com/fluxcd/pkg/tar v0.6.0

go.sum

+2-2
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ github.com/fluxcd/pkg/envsubst v1.0.0 h1:LD86BRNSCGJrvyrH2aX5/pit7RfbFpkzRXogwca
145145
github.com/fluxcd/pkg/envsubst v1.0.0/go.mod h1:VAcb4OxcRdsDix1TRtr/mtTqFGHmNQaOvXQO2REArFQ=
146146
github.com/fluxcd/pkg/http/fetch v0.10.0 h1:Uh1ZrPa4B4EDgi+NFrY7qP6g9vg1O6JHKg3+iJLtt1w=
147147
github.com/fluxcd/pkg/http/fetch v0.10.0/go.mod h1:zZOsAqn7iODap40PVq29mcCPEKjDodYvamEaoN6tV/Q=
148-
github.com/fluxcd/pkg/kustomize v1.9.0 h1:bqS3mXiK1q5TpUtIO5I5b+v/0r96NGJBiearKGUhicA=
149-
github.com/fluxcd/pkg/kustomize v1.9.0/go.mod h1:PBerk0KzZN/IXaGociVp4MSMvsUQB0jR1P2SqSdixz0=
148+
github.com/fluxcd/pkg/kustomize v1.10.0 h1:5upGCY1wgC26chNBqKiaQjtDUm2qJQTDVFLvKNPQb4I=
149+
github.com/fluxcd/pkg/kustomize v1.10.0/go.mod h1:PBerk0KzZN/IXaGociVp4MSMvsUQB0jR1P2SqSdixz0=
150150
github.com/fluxcd/pkg/runtime v0.46.0 h1:+pxFwTk8j8lZIS9Vyc8EJbgvmFp9JqeT6pfLo/0iP98=
151151
github.com/fluxcd/pkg/runtime v0.46.0/go.mod h1:d9BaIjqoHL71fYeZsssrt08UFONGN2WQRaJ/Ay2d1Cc=
152152
github.com/fluxcd/pkg/sourceignore v0.6.0 h1:kD6QXL/upPEX66UpR669yK1Bxr/GtjzmZiqBeYpunUQ=

internal/controller/kustomization_controller.go

+10-4
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
"time"
2828

2929
securejoin "github.com/cyphar/filepath-securejoin"
30+
"github.com/fluxcd/pkg/ssa/normalize"
3031
ssautil "github.com/fluxcd/pkg/ssa/utils"
3132
corev1 "k8s.io/api/core/v1"
3233
apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -293,6 +294,7 @@ func (r *KustomizationReconciler) reconcile(
293294
obj *kustomizev1.Kustomization,
294295
src sourcev1.Source,
295296
patcher *patch.SerialPatcher) error {
297+
log := ctrl.LoggerFrom(ctx)
296298

297299
// Update status with the reconciliation progress.
298300
revision := src.GetArtifact().Revision
@@ -317,7 +319,11 @@ func (r *KustomizationReconciler) reconcile(
317319
return err
318320
}
319321

320-
defer os.RemoveAll(tmpDir)
322+
defer func(path string) {
323+
if err := os.RemoveAll(path); err != nil {
324+
log.Error(err, "failed to remove tmp dir", "path", path)
325+
}
326+
}(tmpDir)
321327

322328
// Download artifact and extract files to the tmp dir.
323329
if err = fetch.NewArchiveFetcherWithLogger(
@@ -653,12 +659,12 @@ func (r *KustomizationReconciler) apply(ctx context.Context,
653659
objects []*unstructured.Unstructured) (bool, *ssa.ChangeSet, error) {
654660
log := ctrl.LoggerFrom(ctx)
655661

656-
if err := ssa.SetNativeKindsDefaults(objects); err != nil {
662+
if err := normalize.UnstructuredList(objects); err != nil {
657663
return false, nil, err
658664
}
659665

660-
if meta := obj.Spec.CommonMetadata; meta != nil {
661-
ssautil.SetCommonMetadata(objects, meta.Labels, meta.Annotations)
666+
if cmeta := obj.Spec.CommonMetadata; cmeta != nil {
667+
ssautil.SetCommonMetadata(objects, cmeta.Labels, cmeta.Annotations)
662668
}
663669

664670
applyOpts := ssa.DefaultApplyOptions()

internal/controller/kustomization_transformer_test.go

+85
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,91 @@ data:
146146
})
147147
}
148148

149+
func TestKustomizationReconciler_NamePrefixSuffix(t *testing.T) {
150+
g := NewWithT(t)
151+
id := "np-" + randStringRunes(5)
152+
revision := "v1.0.0"
153+
resultK := &kustomizev1.Kustomization{}
154+
155+
err := createNamespace(id)
156+
g.Expect(err).NotTo(HaveOccurred(), "failed to create test namespace")
157+
158+
err = createKubeConfigSecret(id)
159+
g.Expect(err).NotTo(HaveOccurred(), "failed to create kubeconfig secret")
160+
161+
manifests := func(name string) []testserver.File {
162+
return []testserver.File{
163+
{
164+
Name: "config.yaml",
165+
Body: fmt.Sprintf(`---
166+
apiVersion: v1
167+
kind: ConfigMap
168+
metadata:
169+
name: %[1]s
170+
annotations:
171+
tenant: test
172+
data:
173+
key: val
174+
`, name),
175+
},
176+
}
177+
}
178+
179+
artifact, err := testServer.ArtifactFromFiles(manifests(id))
180+
g.Expect(err).NotTo(HaveOccurred())
181+
182+
repositoryName := types.NamespacedName{
183+
Name: fmt.Sprintf("cm-%s", randStringRunes(5)),
184+
Namespace: id,
185+
}
186+
187+
err = applyGitRepository(repositoryName, artifact, revision)
188+
g.Expect(err).NotTo(HaveOccurred())
189+
190+
kustomizationKey := types.NamespacedName{
191+
Name: fmt.Sprintf("cm-%s", randStringRunes(5)),
192+
Namespace: id,
193+
}
194+
kustomization := &kustomizev1.Kustomization{
195+
ObjectMeta: metav1.ObjectMeta{
196+
Name: kustomizationKey.Name,
197+
Namespace: kustomizationKey.Namespace,
198+
},
199+
Spec: kustomizev1.KustomizationSpec{
200+
Interval: metav1.Duration{Duration: 2 * time.Minute},
201+
Path: "./",
202+
KubeConfig: &meta.KubeConfigReference{
203+
SecretRef: meta.SecretKeyReference{
204+
Name: "kubeconfig",
205+
},
206+
},
207+
SourceRef: kustomizev1.CrossNamespaceSourceReference{
208+
Name: repositoryName.Name,
209+
Namespace: repositoryName.Namespace,
210+
Kind: sourcev1.GitRepositoryKind,
211+
},
212+
NamePrefix: "prefix-",
213+
NameSuffix: "-suffix",
214+
TargetNamespace: id,
215+
},
216+
}
217+
218+
g.Expect(k8sClient.Create(context.Background(), kustomization)).To(Succeed())
219+
220+
t.Run("sets name prefix and suffix", func(t *testing.T) {
221+
g := NewWithT(t)
222+
g.Eventually(func() bool {
223+
_ = k8sClient.Get(context.Background(), client.ObjectKeyFromObject(kustomization), resultK)
224+
return isReconcileSuccess(resultK)
225+
}, timeout, time.Second).Should(BeTrue())
226+
kstatusCheck.CheckErr(ctx, resultK)
227+
228+
name := fmt.Sprintf("prefix-%s-suffix", id)
229+
var cm corev1.ConfigMap
230+
g.Expect(k8sClient.Get(context.Background(), client.ObjectKey{Name: name, Namespace: id}, &cm)).To(Succeed())
231+
})
232+
}
233+
149234
func TestKustomizationReconciler_KustomizeTransformer(t *testing.T) {
150235
g := NewWithT(t)
151236
id := "transformers-" + randStringRunes(5)

0 commit comments

Comments
 (0)