Home > Back-end >  How to reuse variables in a kubernetes yaml?
How to reuse variables in a kubernetes yaml?

Time:01-25

I have a number of repeated values in my kubernetes yaml file and I wondering if there was a way I could store variables somewhere in the file, ideally at the top, that I can reuse further down

sort of like

variables:
   - appName: &appname myapp
   - buildNumber: &buildno 1.0.23

that I can reuse further down like

labels:
    app: *appname
    tags.datadoghq.com/version:*buildno
containers:
    - name: *appname

...

image: 123456.com:*buildno

if those are possible

I know anchors are a thing in yaml I just couldn't find anything on setting variables

CodePudding user response:

You can't do this in Kubernetes manifests, because you need a processor to manipulate the YAML files. Though you can share the anchors in the same YAML manifest like this:

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: &cmname myconfig
  namespace: &namespace default
  labels:
    name: *cmname
    deployedInNamespace: *namespace
data:
  config.yaml: |
    [myconfig]
    example_field=1

This will result in:

apiVersion: v1
data:
  config.yaml: |
    [myconfig]
    example_field=1
kind: ConfigMap
metadata:
  creationTimestamp: "2023-01-25T10:06:27Z"
  labels:
    deployedInNamespace: default
    name: myconfig
  name: myconfig
  namespace: default
  resourceVersion: "147712"
  uid: 4039cea4-1e64-4d1a-bdff-910d5ff2a485

As you can see the labels name && deployedInNamespace have the values resulted from the anchor evaluation.

Based on your use case description, what you would need is going the Helm chart path and template your manifests. You can then leverage helper functions and easily customize when you want these fields. From my experience, when you have an use case like this, Helm is the way to go, because it will help you customize everything within your manifests when you decide to change something else.

CodePudding user response:

I think helm charts will help you (https://helm.sh/docs/chart_template_guide/values_files/)

CodePudding user response:

I guess there is a similar question with answer. Please check below How to reuse an environment variable in a YAML file?

  • Related