@@ -24,4 +24,116 @@ rec {
24 throw "${shell} is not a shell package"
24 throw "${shell} is not a shell package"
28+ /* Recurse into a list or an attrset, searching for attrs named like
29+ the value of the "attr" parameter, and return an attrset where the
30+ names are the corresponding jq path where the attrs were found and
31+ the values are the values of the attrs.
34+ recursiveGetAttrWithJqPrefix {
37+ irrelevant = "not interesting";
40+ ignored = "ignored attr";
43+ _secret = "/path/to/secret";
48+ } "_secret" -> { ".example[1].relevant.secret" = "/path/to/secret"; }
50+ recursiveGetAttrWithJqPrefix = item: attr:
52+ recurse = prefix: item:
53+ if item ? ${attr} then
54+ nameValuePair prefix item.${attr}
55+ else if isAttrs item then
56+ map (name: recurse (prefix + "." + name) item.${name}) (attrNames item)
57+ else if isList item then
58+ imap0 (index: item: recurse (prefix + "[${toString index}]") item) item
61+ in listToAttrs (flatten (recurse "" item));
63+ /* Takes an attrset and a file path and generates a bash snippet that
64+ outputs a JSON file at the file path with all instances of
66+ { _secret = "/path/to/secret" }
68+ in the attrset replaced with the contents of the file
69+ "/path/to/secret" in the output JSON.
71+ When a configuration option accepts an attrset that is finally
72+ converted to JSON, this makes it possible to let the user define
73+ arbitrary secret values.
76+ If the file "/path/to/secret" contains the string
77+ "topsecretpassword1234",
79+ genJqSecretsReplacementSnippet {
82+ irrelevant = "not interesting";
85+ ignored = "ignored attr";
88+ _secret = "/path/to/secret";
93+ } "/path/to/output.json"
95+ would generate a snippet that, when run, outputs the following
96+ JSON file at "/path/to/output.json":
101+ "irrelevant": "not interesting"
104+ "ignored": "ignored attr",
106+ "secret": "topsecretpassword1234"
112+ genJqSecretsReplacementSnippet = genJqSecretsReplacementSnippet' "_secret";
114+ # Like genJqSecretsReplacementSnippet, but allows the name of the
115+ # attr which identifies the secret to be changed.
116+ genJqSecretsReplacementSnippet' = attr: set: output:
118+ secrets = recursiveGetAttrWithJqPrefix set attr;
120+ if [[ -h '${output}' ]]; then
126+ (imap1 (index: name: "export secret${toString index}=$(<'${secrets.${name}}')")
127+ (attrNames secrets))
129+ + "${pkgs.jq}/bin/jq >'${output}' '"
132+ (imap1 (index: name: ''${name} = $ENV.secret${toString index}'')
133+ (attrNames secrets))
136+ ${builtins.toJSON set}