...

Source file src/sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark/example_test.go

Documentation: sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark

     1  // Copyright 2019 The Kubernetes Authors.
     2  // SPDX-License-Identifier: Apache-2.0
     3  
     4  package starlark_test
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"log"
    10  	"os"
    11  	"path/filepath"
    12  
    13  	"sigs.k8s.io/kustomize/kyaml/fn/runtime/runtimeutil"
    14  	"sigs.k8s.io/kustomize/kyaml/fn/runtime/starlark"
    15  	"sigs.k8s.io/kustomize/kyaml/kio"
    16  	"sigs.k8s.io/kustomize/kyaml/kio/kioutil"
    17  	"sigs.k8s.io/kustomize/kyaml/yaml"
    18  )
    19  
    20  func ExampleFilter_Filter() {
    21  	// input contains the items that will provided to the starlark program
    22  	input := bytes.NewBufferString(`
    23  apiVersion: apps/v1
    24  kind: Deployment
    25  metadata:
    26    name: deployment-1
    27  spec:
    28    template:
    29      spec:
    30        containers:
    31        - name: nginx
    32          image: nginx:1.8.1 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-1"}
    33  ---
    34  apiVersion: apps/v1
    35  kind: Deployment
    36  metadata:
    37    name: deployment-2
    38  spec:
    39    template:
    40      spec:
    41        containers:
    42        - name: nginx
    43          image: nginx:1.7.9 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-2"}
    44  `)
    45  
    46  	// fltr transforms the input using a starlark program
    47  	fltr := &starlark.Filter{
    48  		Name: "annotate",
    49  		Program: `
    50  def run(items):
    51    for item in items:
    52      item["metadata"]["annotations"]["foo"] = "bar"
    53  
    54  run(ctx.resource_list["items"])
    55  `,
    56  	}
    57  
    58  	// output contains the transformed resources
    59  	output := &bytes.Buffer{}
    60  
    61  	// run the fltr against the inputs using a kio.Pipeline
    62  	err := kio.Pipeline{
    63  		Inputs:  []kio.Reader{&kio.ByteReader{Reader: input}},
    64  		Filters: []kio.Filter{fltr},
    65  		Outputs: []kio.Writer{&kio.ByteWriter{Writer: output}}}.Execute()
    66  	if err != nil {
    67  		log.Println(err)
    68  	}
    69  
    70  	fmt.Println(output.String())
    71  
    72  	// Output:
    73  	// apiVersion: apps/v1
    74  	// kind: Deployment
    75  	// metadata:
    76  	//   name: deployment-1
    77  	//   annotations:
    78  	//     foo: bar
    79  	//     internal.config.kubernetes.io/path: 'deployment_deployment-1.yaml'
    80  	//     config.kubernetes.io/path: 'deployment_deployment-1.yaml'
    81  	// spec:
    82  	//   template:
    83  	//     spec:
    84  	//       containers:
    85  	//       - name: nginx
    86  	//         image: nginx:1.8.1 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-1"}
    87  	//---
    88  	// apiVersion: apps/v1
    89  	// kind: Deployment
    90  	// metadata:
    91  	//   name: deployment-2
    92  	//   annotations:
    93  	//     foo: bar
    94  	//     internal.config.kubernetes.io/path: 'deployment_deployment-2.yaml'
    95  	//     config.kubernetes.io/path: 'deployment_deployment-2.yaml'
    96  	// spec:
    97  	//   template:
    98  	//     spec:
    99  	//       containers:
   100  	//       - name: nginx
   101  	//         image: nginx:1.7.9 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-2"}
   102  }
   103  
   104  func ExampleFilter_Filter_functionConfig() {
   105  	// input contains the items that will provided to the starlark program
   106  	input := bytes.NewBufferString(`
   107  apiVersion: apps/v1
   108  kind: Deployment
   109  metadata:
   110    name: deployment-1
   111  spec:
   112    template:
   113      spec:
   114        containers:
   115        - name: nginx
   116          image: nginx:1.8.1 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-1"}
   117  ---
   118  apiVersion: apps/v1
   119  kind: Deployment
   120  metadata:
   121    name: deployment-2
   122  spec:
   123    template:
   124      spec:
   125        containers:
   126        - name: nginx
   127          image: nginx:1.7.9 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-2"}
   128  `)
   129  
   130  	fc, err := yaml.Parse(`
   131  kind: AnnotationSetter
   132  spec:
   133    value: "hello world"
   134  `)
   135  	if err != nil {
   136  		log.Println(err)
   137  	}
   138  
   139  	// fltr transforms the input using a starlark program
   140  	fltr := &starlark.Filter{
   141  		Name: "annotate",
   142  		Program: `
   143  def run(items, value):
   144    for item in items:
   145      item["metadata"]["annotations"]["foo"] = value
   146  
   147  run(ctx.resource_list["items"], ctx.resource_list["functionConfig"]["spec"]["value"])
   148  `,
   149  		FunctionFilter: runtimeutil.FunctionFilter{FunctionConfig: fc},
   150  	}
   151  
   152  	// output contains the transformed resources
   153  	output := &bytes.Buffer{}
   154  
   155  	// run the fltr against the inputs using a kio.Pipeline
   156  	err = kio.Pipeline{
   157  		Inputs:  []kio.Reader{&kio.ByteReader{Reader: input}},
   158  		Filters: []kio.Filter{fltr},
   159  		Outputs: []kio.Writer{&kio.ByteWriter{Writer: output}}}.Execute()
   160  	if err != nil {
   161  		log.Println(err)
   162  	}
   163  
   164  	fmt.Println(output.String())
   165  
   166  	// Output:
   167  	// apiVersion: apps/v1
   168  	// kind: Deployment
   169  	// metadata:
   170  	//   name: deployment-1
   171  	//   annotations:
   172  	//     foo: hello world
   173  	//     internal.config.kubernetes.io/path: 'deployment_deployment-1.yaml'
   174  	//     config.kubernetes.io/path: 'deployment_deployment-1.yaml'
   175  	// spec:
   176  	//   template:
   177  	//     spec:
   178  	//       containers:
   179  	//       - name: nginx
   180  	//         image: nginx:1.8.1 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-1"}
   181  	//---
   182  	// apiVersion: apps/v1
   183  	// kind: Deployment
   184  	// metadata:
   185  	//   name: deployment-2
   186  	//   annotations:
   187  	//     foo: hello world
   188  	//     internal.config.kubernetes.io/path: 'deployment_deployment-2.yaml'
   189  	//     config.kubernetes.io/path: 'deployment_deployment-2.yaml'
   190  	// spec:
   191  	//   template:
   192  	//     spec:
   193  	//       containers:
   194  	//       - name: nginx
   195  	//         image: nginx:1.7.9 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-2"}
   196  }
   197  
   198  // ExampleFilter_Filter_file applies a starlark program in a local file to a collection of
   199  // resource configuration read from a directory.
   200  func ExampleFilter_Filter_file() {
   201  	// setup the configuration
   202  	d, err := os.MkdirTemp("", "")
   203  	if err != nil {
   204  		log.Println(err)
   205  	}
   206  	defer os.RemoveAll(d)
   207  
   208  	err = os.WriteFile(filepath.Join(d, "deploy1.yaml"), []byte(`
   209  apiVersion: apps/v1
   210  kind: Deployment
   211  metadata:
   212    name: deployment-1
   213  spec:
   214    template:
   215      spec:
   216        containers:
   217        - name: nginx
   218          image: nginx:1.8.1 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-1"}
   219  `), 0600)
   220  	if err != nil {
   221  		log.Println(err)
   222  	}
   223  
   224  	err = os.WriteFile(filepath.Join(d, "deploy2.yaml"), []byte(`
   225  apiVersion: apps/v1
   226  kind: Deployment
   227  metadata:
   228    name: deployment-2
   229  spec:
   230    template:
   231      spec:
   232        containers:
   233        - name: nginx
   234          image: nginx:1.7.9 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-2"}
   235  `), 0600)
   236  	if err != nil {
   237  		log.Println(err)
   238  	}
   239  
   240  	err = os.WriteFile(filepath.Join(d, "annotate.star"), []byte(`
   241  def run(items):
   242    for item in items:
   243      item["metadata"]["annotations"]["foo"] = "bar"
   244  
   245  run(ctx.resource_list["items"])
   246  `), 0600)
   247  	if err != nil {
   248  		log.Println(err)
   249  	}
   250  
   251  	fltr := &starlark.Filter{
   252  		Name: "annotate",
   253  		Path: filepath.Join(d, "annotate.star"),
   254  	}
   255  
   256  	// output contains the transformed resources
   257  	output := &bytes.Buffer{}
   258  
   259  	// run the fltr against the inputs using a kio.Pipeline
   260  	err = kio.Pipeline{
   261  		Inputs:  []kio.Reader{&kio.LocalPackageReader{PackagePath: d}},
   262  		Filters: []kio.Filter{fltr},
   263  		Outputs: []kio.Writer{&kio.ByteWriter{
   264  			Writer: output,
   265  			ClearAnnotations: []string{
   266  				kioutil.PathAnnotation,
   267  				kioutil.LegacyPathAnnotation,
   268  			},
   269  		}}}.Execute()
   270  	if err != nil {
   271  		log.Println(err)
   272  	}
   273  
   274  	fmt.Println(output.String())
   275  
   276  	// Output:
   277  	// apiVersion: apps/v1
   278  	// kind: Deployment
   279  	// metadata:
   280  	//   name: deployment-1
   281  	//   annotations:
   282  	//     foo: bar
   283  	// spec:
   284  	//   template:
   285  	//     spec:
   286  	//       containers:
   287  	//       - name: nginx
   288  	//         image: nginx:1.8.1 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-1"}
   289  	//---
   290  	// apiVersion: apps/v1
   291  	// kind: Deployment
   292  	// metadata:
   293  	//   name: deployment-2
   294  	//   annotations:
   295  	//     foo: bar
   296  	// spec:
   297  	//   template:
   298  	//     spec:
   299  	//       containers:
   300  	//       - name: nginx
   301  	//         image: nginx:1.7.9 # {"$ref": "#/definitions/io.k8s.cli.substitutions.image-2"}
   302  }
   303  

View as plain text