diff --git a/default.nix b/default.nix index 9d172f6..d3c9239 100644 --- a/default.nix +++ b/default.nix @@ -11,7 +11,7 @@ let args = { inherit pkgs; name = "default"; - k8s = { inherit loadJSON loadYAML toBase64; }; + k8s = { inherit loadJSON loadYAML toBase64 mkValueOrSecretOption; }; }; }; diff --git a/lib.nix b/lib.nix index eb83a20..7cd283a 100644 --- a/lib.nix +++ b/lib.nix @@ -29,4 +29,29 @@ rec { toBase64 = value: builtins.readFile (pkgs.runCommand "value-to-b64" {} "echo '${value}' | ${pkgs.coreutils}/bin/base64 -w0 > $out"); + + mkValueOrSecretOption = {...}@options: mkOption ({ + type = types.either types.str (types.submodule { + options.secret = mkOption { + description = "Name of the secret where password is stored"; + type = types.str; + }; + + options.key = mkOption { + description = "Name of the key where password is stored"; + type = types.str; + default = "password"; + }; + }); + + apply = value: + if isAttrs value + then { + valueFrom.secretKeyRef = { + name = value.secret; + key = value.key; + }; + } + else {inherit value;}; + } // options); } diff --git a/test/modules.nix b/test/modules.nix index 147810a..b2a2c5e 100644 --- a/test/modules.nix +++ b/test/modules.nix @@ -1,5 +1,6 @@ {lib, k8s, ...}: +with k8s; with lib; { @@ -11,11 +12,16 @@ with lib; type = types.int; default = 80; }; + + password = mkValueOrSecretOption { + description = "Nginx simple auth credentials"; + default.secret = "test"; + }; }; config = { kubernetes.resources.deployments.nginx = mkMerge [ - (k8s.loadJSON ./deployment.json) + (loadJSON ./deployment.json) { metadata.name = "${name}-nginx"; @@ -23,15 +29,12 @@ with lib; containerPort = config.port; }; - spec.template.spec.containers.nginx.env.name.valueFrom.secretKeyRef = { - name = config.kubernetes.resources.configMaps.nginx.metadata.name; - key = "somekey"; - }; + spec.template.spec.containers.nginx.env.name = config.password; } ]; kubernetes.resources.configMaps.nginx = mkMerge [ - (k8s.loadJSON ./configMap.json) + (loadJSON ./configMap.json) { metadata.name = mkForce "${name}-nginx"; } @@ -45,7 +48,7 @@ with lib; configuration.port = 8080; }; - kubernetes.resources.services.nginx = k8s.loadJSON ./service.json; + kubernetes.resources.services.nginx = loadJSON ./service.json; kubernetes.defaultModuleConfiguration = [{ kubernetes.defaults.deployments.spec.replicas = 3;