jsonnet

How to get all subdirectories in jsonnet?


I'm creating a gitlab-ci.yml file dynamically with jsonnet. Now I want to create a job for each directory in my customers-directory. For that I want to read all directory names into an array.

How do I do that?

Pseudo code would look like this: customers:: [c for c in getAllDirectories("path/to/customers-directory")]

Thank you very much!


Solution

  • By design jsonnet doesn't have any means to read "environmental data" (broadly speaking: files/dirs/devices, env vars, etc). It does, however, provide ways for "injecting" this data via CLI args, please do read https://jsonnet.org/learning/tutorial.html#parameterize-entire-config for details.

    In your case, this could be achieved by the below example code:

    Test dirs

    $ mkdir -p /tmp/customers.d/{foo,bar,baz}
    $ ls -F /tmp/customers.d/
    bar/  baz/  foo/
    

    Code (dirs.jsonnet)

    // Expect ext-var containing new-line separated list of dirs
    local customers = std.split(std.extVar('customers'), '\n');
    
    customers
    

    CLI run and output

    $ jsonnet --ext-str customers="$(find /tmp/customers.d/ -mindepth 1 -maxdepth 1 -type d -printf '%f\n')" dirs.jsonnet
    [
       "bar",
       "foo",
       "baz"
    ]