0

I am setting an environment variable inside a makefile. makeflie:
...
export KINDPORT=30000
...

I want to pass it to the YAML file that I am using (for kind cluster configuration file):

...
extraPortMappings:

  • containerPort: ${KINDPORT}
    hostPort: ${KINDPORT}
    protocol: TCP

...

What is the correct syntax for this?

kfirt
  • 11
  • 3
  • This doesn't appear to be related to makefiles at all. Whether an environment variable can be expanded in any type of file, including a YAML file, depends on the tool parsing the YAML so it's a question for the users of that tool. However, the syntax is virtually always `${VARNAME}`, not `{$VARNAME}`. – MadScientist Nov 07 '22 at 15:01
  • Yes, you are right is less related to makefile and I fixed the typo in my question, but with this code, I get the following error: "line 12: cannot unmarshal !!str `${KINDP...` into int32" – kfirt Nov 07 '22 at 17:17
  • Looks like that string is not getting replaced with the value of the environment variable. You'll have to check with the tool that's parsing YAML to see how, or even if, it's possible. – MadScientist Nov 07 '22 at 20:04

1 Answers1

0

YAML does not provide builtin support for injecting any values from outside. You can do one of two things:

  • Generate the YAML file in the Makefile. You would write a template file, e.g. myFile.yaml.tmpl, and let make substitute variables in there to generate myFile.yaml. The following example uses envsubst which recognizes $var and ${var} and seems close to what you want.
myFile.yaml: KINDPORT=30000
myFile.yaml: myFile.yaml.tmpl
    envsubst < $< > $@
  • Pre-process or post-process the YAML file while loading. This depends on the application loading the YAML file. Some applications do have such capabilities, refer to the documentation of the target application. If the YAML file is loaded by code you write, you can do either.

    pre-processing means that you run a templating engine or similar processor (like envsubst above) on the file's content before deserializing. This is preferrable when your values are all simple scalars and probably the right thing for your use-case.

    post-processing means that you first deserialize the YAML and then process scalars that may contain variable references in the resulting structure. This is useful if you want to inject complex values (e.g. mappings or sequences). The drawback is that your variable syntax must not contain special YAML characters, which would otherwise be processed via YAML.

flyx
  • 35,506
  • 7
  • 89
  • 126