Created
August 28, 2024 13:48
-
-
Save hamza-m-masood/077d34a35a5892fcdab93eba4524f4e2 to your computer and use it in GitHub Desktop.
modifying annotation and label using KRM function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"log" | |
"os" | |
"sigs.k8s.io/kustomize/kyaml/kio" | |
"sigs.k8s.io/kustomize/kyaml/yaml" | |
) | |
func main() { | |
input := bytes.NewReader([]byte(`apiVersion: apps/v1 | |
kind: Deployment | |
metadata: | |
name: nginx | |
labels: | |
app: nginx | |
spec: | |
replicas: 3 | |
selector: | |
matchLabels: | |
app: nginx | |
template: | |
metadata: | |
labels: | |
app: nginx | |
spec: | |
containers: | |
- name: nginx | |
image: nginx:1.7.9 | |
ports: | |
- containerPort: 80 | |
--- | |
apiVersion: v1 | |
kind: Service | |
metadata: | |
name: nginx | |
spec: | |
selector: | |
app: nginx | |
ports: | |
- protocol: TCP | |
port: 80 | |
targetPort: 80 | |
`)) | |
// setAnnotationFn | |
setAnnotationFn := kio.FilterFunc(func(operand []*yaml.RNode) ([]*yaml.RNode, error) { | |
for i := range operand { | |
resource := operand[i] | |
_, err := resource.Pipe(yaml.SetAnnotation("foo", "bar")) | |
resource.Pipe(yaml.SetK8sNamespace("testinghamza")) | |
if err != nil { | |
return nil, err | |
} | |
} | |
return operand, nil | |
}) | |
setLabelFn := kio.FilterFunc(func(operand []*yaml.RNode) ([]*yaml.RNode, error) { | |
for i := range operand { | |
resource := operand[i] | |
_, err := resource.Pipe(yaml.SetLabel("hi", "how are you")) | |
if err != nil { | |
return nil, err | |
} | |
} | |
return operand, nil | |
}) | |
err := kio.Pipeline{ | |
Inputs: []kio.Reader{&kio.ByteReader{Reader: input}}, | |
Filters: []kio.Filter{setAnnotationFn, setLabelFn}, | |
Outputs: []kio.Writer{kio.ByteWriter{Writer: os.Stdout}}, | |
}.Execute() | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment