1
0
forked from clan/clan-core

Merge pull request 'add: lib/facts.nix' (#1681) from kenji/clan-core:feature/clanLib into main

Reviewed-on: clan/clan-core#1681
This commit is contained in:
kenji 2024-07-02 11:34:26 +00:00
commit 129db95426
2 changed files with 74 additions and 1 deletions

View File

@ -6,8 +6,9 @@
}:
{
evalClanModules = import ./eval-clan-modules { inherit clan-core nixpkgs lib; };
buildClan = import ./build-clan { inherit clan-core lib nixpkgs; };
facts = import ./facts.nix { inherit lib; };
inventory = import ./inventory { inherit lib clan-core; };
jsonschema = import ./jsonschema { inherit lib; };
modules = import ./description.nix { inherit clan-core lib; };
buildClan = import ./build-clan { inherit clan-core lib nixpkgs; };
}

72
lib/facts.nix Normal file
View File

@ -0,0 +1,72 @@
{ lib, ... }:
machineDir:
let
allMachineNames = lib.mapAttrsToList (name: _: name) (builtins.readDir machineDir);
getFactPath = fact: machine: "${machineDir}/${machine}/facts/${fact}";
readFact =
fact: machine:
let
path = getFactPath fact machine;
in
if builtins.pathExists path then builtins.readFile path else null;
# Example:
#
# readFactFromAllMachines zerotier-ip
# => {
# machineA = "1.2.3.4";
# machineB = "5.6.7.8";
# };
readFactFromAllMachines =
fact:
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";
# };
# };
readFactsFromAllMachines =
facts:
let
# machine -> fact -> factvalue
machinesFactsAttrs = lib.genAttrs allMachineNames (
machine: lib.genAttrs facts (fact: readFact fact machine)
);
# remove all machines which don't have all facts set
filteredMachineFactAttrs = lib.filterAttrs (
_machine: values: builtins.all (fact: values.${fact} != null) facts
) machinesFactsAttrs;
in
filteredMachineFactAttrs;
in
{
inherit
allMachineNames
getFactPath
readFact
readFactFromAllMachines
readFactsFromAllMachines
;
}