Add static value source for replacement

Introduces `sourceValue` on replacement object for replacing from a
static value instead of sourcing from another object.

Solves #5516
This commit is contained in:
Ramon Cunyat
2024-03-28 20:22:12 +01:00
committed by Ramon Cuñat
parent cc9dd34216
commit 6c27970019
3 changed files with 75 additions and 1 deletions

View File

@@ -23,7 +23,7 @@ type Filter struct {
// Filter replaces values of targets with values from sources
func (f Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
for i, r := range f.Replacements {
if r.Source == nil || r.Targets == nil {
if (r.SourceValue == nil && r.Source == nil) || r.Targets == nil {
return nil, fmt.Errorf("replacements must specify a source and at least one target")
}
value, err := getReplacement(nodes, &f.Replacements[i])
@@ -39,6 +39,13 @@ func (f Filter) Filter(nodes []*yaml.RNode) ([]*yaml.RNode, error) {
}
func getReplacement(nodes []*yaml.RNode, r *types.Replacement) (*yaml.RNode, error) {
if r.SourceValue != nil && r.Source != nil {
return nil, fmt.Errorf("value and resource selectors are mutually exclusive")
}
if r.SourceValue != nil {
return yaml.NewScalarRNode(*r.SourceValue), nil
}
source, err := selectSourceNode(nodes, r.Source)
if err != nil {
return nil, err

View File

@@ -2829,6 +2829,70 @@ spec:
create: true
`,
expectedErr: "unable to find or create field \"spec.tls.5.hosts.5\" in replacement target: index 5 specified but only 0 elements found",
}, "replace with static value": {
input: `apiVersion: v1
kind: Deployment
metadata:
name: deploy
spec:
template:
spec:
containers:
- image: nginx:1.7.9
name: nginx-tagged
- image: postgres:1.8.0
name: postgresdb
`,
replacements: `replacements:
- sourceValue: custom/postgres:1.9.0
targets:
- select:
kind: Deployment
name: deploy
fieldPaths:
- spec.template.spec.containers.[name=postgresdb].image
`,
expected: `apiVersion: v1
kind: Deployment
metadata:
name: deploy
spec:
template:
spec:
containers:
- image: nginx:1.7.9
name: nginx-tagged
- image: custom/postgres:1.9.0
name: postgresdb
`,
}, "source value and selector error": {
input: `apiVersion: v1
kind: Deployment
metadata:
name: deploy
spec:
replicas: 1
template:
spec:
containers:
- image: nginx:1.7.9
name: nginx-tagged
- image: postgres:1.8.0
name: postgresdb
`,
replacements: `replacements:
- source:
kind: Deployment
name: deploy
sourceValue: 2
targets:
- select:
kind: Deployment
name: deploy
fieldPaths:
- spec.replicas
`,
expectedErr: "value and resource selectors are mutually exclusive",
},
}

View File

@@ -20,6 +20,9 @@ type Replacement struct {
// The N fields to write the value to.
Targets []*TargetSelector `json:"targets,omitempty" yaml:"targets,omitempty"`
// Used to define an static value
SourceValue *string `json:"sourceValue,omitempty" yaml:"sourceValue,omitempty"`
}
// SourceSelector is the source of the replacement transformer.