Search code examples
javajsonnet

How to set a hostname in a jsonnet file?


I am trying to get the hang of jsonnet files. So far all I have is hard-coded values but what if I wanted to get the hostname for a Java application. For example in Java I would just do:

String hostName = System.getenv("HOSTNAME");

But obviously I can't just have a key-value pair like the following JSON in a jsonnet file.

{name: "hostname", value:System.getenv("HOSTNAME")} 

I need a bit of help in understanding how I can do this.

I have looked up std.extvar(x) but the examples I look at just arent clear to me for whatever reason. Is this method relevant? Otherwise, I'm not really sure.


Solution

  • Jsonnet requires all parameters to be passed explicitly. To use a hostname in your Jsonnet code, you need to pass it to the interpreter. For example you can run it as follows:

    ❯ jsonnet --ext-str "HOSTNAME=$HOST" foo.jsonnet
    

    foo.jsonnet:

    std.extVar('HOSTNAME')
    

    You can also use top-level-arguments mechanism to a similar effect (top-level-arguments are passed as function arguments to the evaluated script.

    Please see: https://jsonnet.org/learning/tutorial.html#parameterize-entire-config for more in-depth explanation of these features.

    FYI not being able to just grab any environment variable or access the system directly is very much by design. The result of Jsonnet evaluation depends only on the code and explicitly passed parameters. This has a lot of benefits, such as the following:

    • You can easily evaluate on another machine, even on a completely different platform and get exactly the same result.
    • You are never locked in to configuration on any particular machine – you can always pass any parameters on any machine (very useful for development and debugging).
    • Avoiding surprises – the evaluation won't break one day, because some random aspect of local configuration changed and some deep part of the code happens to depend on it – all parameters are accounted for.