1
0
forked from clan/clan-core
clan-core/lib/facts.nix

72 lines
1.7 KiB
Nix
Raw Normal View History

2024-07-02 09:26:50 +00:00
{ lib, ... }:
machineDir:
2024-06-19 12:57:53 +00:00
let
allMachineNames = lib.mapAttrsToList (name: _: name) (builtins.readDir machineDir);
2024-07-02 09:26:50 +00:00
getFactPath = fact: machine: "${machineDir}/${machine}/facts/${fact}";
2024-06-19 12:57:53 +00:00
2024-07-02 09:26:50 +00:00
readFact =
fact: machine:
2024-06-19 12:57:53 +00:00
let
path = getFactPath fact machine;
in
2024-07-02 09:26:50 +00:00
if builtins.pathExists path then builtins.readFile path else null;
2024-06-19 12:57:53 +00:00
# Example:
#
# readFactFromAllMachines zerotier-ip
# => {
# machineA = "1.2.3.4";
# machineB = "5.6.7.8";
# };
2024-07-02 09:26:50 +00:00
readFactFromAllMachines =
fact:
2024-06-19 12:57:53 +00:00
let
machines = allMachineNames;
facts = lib.genAttrs machines (readFact fact);
filteredFacts = lib.filterAttrs (_machine: fact: fact != null) facts;
in
filteredFacts;
# all given facts are are set and factvalues are never null.
#
# Example:
#
# readFactsFromAllMachines [ "zerotier-ip" "syncthing.pub" ]
# => {
# machineA =
# {
# "zerotier-ip" = "1.2.3.4";
# "synching.pub" = "1234";
# };
# machineB =
# {
# "zerotier-ip" = "5.6.7.8";
# "synching.pub" = "23456719";
# };
# };
2024-07-02 09:26:50 +00:00
readFactsFromAllMachines =
facts:
2024-06-19 12:57:53 +00:00
let
# machine -> fact -> factvalue
2024-07-02 09:26:50 +00:00
machinesFactsAttrs = lib.genAttrs allMachineNames (
machine: lib.genAttrs facts (fact: readFact fact machine)
);
2024-06-19 12:57:53 +00:00
# remove all machines which don't have all facts set
2024-07-02 09:26:50 +00:00
filteredMachineFactAttrs = lib.filterAttrs (
_machine: values: builtins.all (fact: values.${fact} != null) facts
) machinesFactsAttrs;
2024-06-19 12:57:53 +00:00
in
filteredMachineFactAttrs;
in
2024-07-02 09:26:50 +00:00
{
inherit
allMachineNames
getFactPath
readFact
readFactFromAllMachines
readFactsFromAllMachines
;
}