mirror of
https://github.com/kubernetes-sigs/kustomize.git
synced 2026-06-11 17:12:51 +00:00
Function framework support for patching containers
This commit is contained in:
60
kyaml/fn/framework/containers.go
Normal file
60
kyaml/fn/framework/containers.go
Normal file
@@ -0,0 +1,60 @@
|
||||
// Copyright 2019 The Kubernetes Authors.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package framework
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"text/template"
|
||||
|
||||
"sigs.k8s.io/kustomize/kyaml/errors"
|
||||
"sigs.k8s.io/kustomize/kyaml/sets"
|
||||
"sigs.k8s.io/kustomize/kyaml/yaml"
|
||||
"sigs.k8s.io/kustomize/kyaml/yaml/merge2"
|
||||
)
|
||||
|
||||
// PatchTemplateContainers executes t as a template and patches each container in each resource
|
||||
// with the result.
|
||||
func PatchTemplateContainers(resources []*yaml.RNode, t string, input interface{}, containers ...string) error {
|
||||
resourcePatch := template.Must(template.New("containers").Parse(t))
|
||||
var b bytes.Buffer
|
||||
if err := resourcePatch.Execute(&b, input); err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
patch, err := yaml.Parse(b.String())
|
||||
if err != nil {
|
||||
return errors.WrapPrefixf(err, b.String())
|
||||
}
|
||||
return PatchContainers(resources, patch, containers...)
|
||||
}
|
||||
|
||||
// PatchContainers applies patch to each container in each resource.
|
||||
func PatchContainers(resources []*yaml.RNode, patch *yaml.RNode, containers ...string) error {
|
||||
names := sets.String{}
|
||||
names.Insert(containers...)
|
||||
|
||||
for i := range resources {
|
||||
containers, err := resources[i].Pipe(yaml.Lookup("spec", "template", "spec", "containers"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
if containers == nil {
|
||||
continue
|
||||
}
|
||||
err = containers.VisitElements(func(node *yaml.RNode) error {
|
||||
f := node.Field("name")
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
if names.Len() > 0 && !names.Has(yaml.GetValue(f.Value)) {
|
||||
return nil
|
||||
}
|
||||
_, err := merge2.Merge(patch, node, yaml.MergeOptions{})
|
||||
return errors.Wrap(err)
|
||||
})
|
||||
if err != nil {
|
||||
return errors.Wrap(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user