...
1
2
3
4 package builtins
5
6 import (
7 "errors"
8
9 "sigs.k8s.io/kustomize/api/filters/suffix"
10 "sigs.k8s.io/kustomize/api/resmap"
11 "sigs.k8s.io/kustomize/api/types"
12 "sigs.k8s.io/kustomize/kyaml/resid"
13 "sigs.k8s.io/kustomize/kyaml/yaml"
14 )
15
16
17 type SuffixTransformerPlugin struct {
18 Suffix string `json:"suffix,omitempty" yaml:"suffix,omitempty"`
19 FieldSpecs types.FsSlice `json:"fieldSpecs,omitempty" yaml:"fieldSpecs,omitempty"`
20 }
21
22
23 var suffixFieldSpecsToSkip = types.FsSlice{
24 {Gvk: resid.Gvk{Kind: "CustomResourceDefinition"}},
25 {Gvk: resid.Gvk{Group: "apiregistration.k8s.io", Kind: "APIService"}},
26 {Gvk: resid.Gvk{Kind: "Namespace"}},
27 }
28
29 func (p *SuffixTransformerPlugin) Config(
30 _ *resmap.PluginHelpers, c []byte) (err error) {
31 p.Suffix = ""
32 p.FieldSpecs = nil
33 err = yaml.Unmarshal(c, p)
34 if err != nil {
35 return
36 }
37 if p.FieldSpecs == nil {
38 return errors.New("fieldSpecs is not expected to be nil")
39 }
40 return
41 }
42
43 func (p *SuffixTransformerPlugin) Transform(m resmap.ResMap) error {
44
45
46
47 for _, r := range m.Resources() {
48
49 if p.shouldSkip(r.OrgId()) {
50 continue
51 }
52 id := r.OrgId()
53
54
55 for _, fs := range p.FieldSpecs {
56
57 if !id.IsSelected(&fs.Gvk) {
58 continue
59 }
60
61 if fs.Path == "metadata/name" {
62
63
64
65
66 r.AddNameSuffix(p.Suffix)
67 if p.Suffix != "" {
68
69
70
71 r.StorePreviousId()
72 }
73 }
74 if err := r.ApplyFilter(suffix.Filter{
75 Suffix: p.Suffix,
76 FieldSpec: fs,
77 }); err != nil {
78 return err
79 }
80 }
81 }
82 return nil
83 }
84
85 func (p *SuffixTransformerPlugin) shouldSkip(id resid.ResId) bool {
86 for _, path := range suffixFieldSpecsToSkip {
87 if id.IsSelected(&path.Gvk) {
88 return true
89 }
90 }
91 return false
92 }
93
94 func NewSuffixTransformerPlugin() resmap.TransformerPlugin {
95 return &SuffixTransformerPlugin{}
96 }
97
View as plain text