1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
|
{ config, lib, pkgs, ... }:
let
cfg = config.services.netbox;
pythonFmt = pkgs.formats.pythonVars {};
staticDir = cfg.dataDir + "/static";
settingsFile = pythonFmt.generate "netbox-settings.py" cfg.settings;
extraConfigFile = pkgs.writeTextFile {
name = "netbox-extraConfig.py";
text = cfg.extraConfig;
};
configFile = pkgs.concatText "configuration.py" [ settingsFile extraConfigFile ];
pkg = (cfg.package.overrideAttrs (old: {
installPhase = old.installPhase + ''
ln -s ${configFile} $out/opt/netbox/netbox/netbox/configuration.py
'' + lib.optionalString cfg.enableLdap ''
ln -s ${cfg.ldapConfigPath} $out/opt/netbox/netbox/netbox/ldap_config.py
'';
})).override {
inherit (cfg) plugins;
};
netboxManageScript = with pkgs; (writeScriptBin "netbox-manage" ''
#!${stdenv.shell}
export PYTHONPATH=${pkg.pythonPath}
sudo -u netbox ${pkg}/bin/netbox "$@"
'');
in {
options.services.netbox = {
enable = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Enable Netbox.
This module requires a reverse proxy that serves `/static` separately.
See this [example](https://github.com/netbox-community/netbox/blob/develop/contrib/nginx.conf/) on how to configure this.
'';
};
settings = lib.mkOption {
description = ''
Configuration options to set in `configuration.py`.
See the [documentation](https://docs.netbox.dev/en/stable/configuration/) for more possible options.
'';
default = { };
type = lib.types.submodule {
freeformType = pythonFmt.type;
options = {
ALLOWED_HOSTS = lib.mkOption {
type = with lib.types; listOf str;
default = ["*"];
description = ''
A list of valid fully-qualified domain names (FQDNs) and/or IP
addresses that can be used to reach the NetBox service.
'';
};
};
};
};
listenAddress = lib.mkOption {
type = lib.types.str;
default = "[::1]";
description = ''
Address the server will listen on.
'';
};
package = lib.mkOption {
type = lib.types.package;
default =
if lib.versionAtLeast config.system.stateVersion "24.05"
then pkgs.netbox_3_7
else if lib.versionAtLeast config.system.stateVersion "23.11"
then pkgs.netbox_3_6
else if lib.versionAtLeast config.system.stateVersion "23.05"
then pkgs.netbox_3_5
else pkgs.netbox_3_3;
defaultText = lib.literalExpression ''
if lib.versionAtLeast config.system.stateVersion "24.05"
then pkgs.netbox_3_7
else if lib.versionAtLeast config.system.stateVersion "23.11"
then pkgs.netbox_3_6
else if lib.versionAtLeast config.system.stateVersion "23.05"
then pkgs.netbox_3_5
else pkgs.netbox_3_3;
'';
description = ''
NetBox package to use.
'';
};
port = lib.mkOption {
type = lib.types.port;
default = 8001;
description = ''
Port the server will listen on.
'';
};
plugins = lib.mkOption {
type = with lib.types; functionTo (listOf package);
default = _: [];
defaultText = lib.literalExpression ''
python3Packages: with python3Packages; [];
'';
description = ''
List of plugin packages to install.
'';
};
dataDir = lib.mkOption {
type = lib.types.str;
default = "/var/lib/netbox";
description = ''
Storage path of netbox.
'';
};
secretKeyFile = lib.mkOption {
type = lib.types.path;
description = ''
Path to a file containing the secret key.
'';
};
extraConfig = lib.mkOption {
type = lib.types.lines;
default = "";
description = ''
Additional lines of configuration appended to the `configuration.py`.
See the [documentation](https://docs.netbox.dev/en/stable/configuration/) for more possible options.
'';
};
enableLdap = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Enable LDAP-Authentication for Netbox.
This requires a configuration file being pass through `ldapConfigPath`.
'';
};
ldapConfigPath = lib.mkOption {
type = lib.types.path;
default = "";
description = ''
Path to the Configuration-File for LDAP-Authentication, will be loaded as `ldap_config.py`.
See the [documentation](https://netbox.readthedocs.io/en/stable/installation/6-ldap/#configuration) for possible options.
'';
example = ''
import ldap
from django_auth_ldap.config import LDAPSearch, PosixGroupType
AUTH_LDAP_SERVER_URI = "ldaps://ldap.example.com/"
AUTH_LDAP_USER_SEARCH = LDAPSearch(
"ou=accounts,ou=posix,dc=example,dc=com",
ldap.SCOPE_SUBTREE,
"(uid=%(user)s)",
)
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
"ou=groups,ou=posix,dc=example,dc=com",
ldap.SCOPE_SUBTREE,
"(objectClass=posixGroup)",
)
AUTH_LDAP_GROUP_TYPE = PosixGroupType()
# Mirror LDAP group assignments.
AUTH_LDAP_MIRROR_GROUPS = True
# For more granular permissions, we can map LDAP groups to Django groups.
AUTH_LDAP_FIND_GROUP_PERMS = True
'';
};
keycloakClientSecret = lib.mkOption {
type = with lib.types; nullOr path;
default = null;
description = ''
File that contains the keycloak client secret.
'';
};
};
config = lib.mkIf cfg.enable {
services.netbox = {
plugins = lib.mkIf cfg.enableLdap (ps: [ ps.django-auth-ldap ]);
settings = {
STATIC_ROOT = staticDir;
MEDIA_ROOT = "${cfg.dataDir}/media";
REPORTS_ROOT = "${cfg.dataDir}/reports";
SCRIPTS_ROOT = "${cfg.dataDir}/scripts";
GIT_PATH = "${pkgs.gitMinimal}/bin/git";
DATABASE = {
NAME = "netbox";
USER = "netbox";
HOST = "/run/postgresql";
};
# Redis database settings. Redis is used for caching and for queuing
# background tasks such as webhook events. A separate configuration
# exists for each. Full connection details are required in both
# sections, and it is strongly recommended to use two separate database
# IDs.
REDIS = {
tasks = {
URL = "unix://${config.services.redis.servers.netbox.unixSocket}?db=0";
SSL = false;
};
caching = {
URL = "unix://${config.services.redis.servers.netbox.unixSocket}?db=1";
SSL = false;
};
};
REMOTE_AUTH_BACKEND = lib.mkIf cfg.enableLdap "netbox.authentication.LDAPBackend";
LOGGING = lib.mkDefault {
version = 1;
formatters.precise.format = "[%(levelname)s@%(name)s] %(message)s";
handlers.console = {
class = "logging.StreamHandler";
formatter = "precise";
};
# log to console/systemd instead of file
root = {
level = "INFO";
handlers = [ "console" ];
};
};
};
extraConfig = ''
with open("${cfg.secretKeyFile}", "r") as file:
SECRET_KEY = file.readline()
'' + (lib.optionalString (cfg.keycloakClientSecret != null) ''
with open("${cfg.keycloakClientSecret}", "r") as file:
SOCIAL_AUTH_KEYCLOAK_SECRET = file.readline()
'');
};
services.redis.servers.netbox.enable = true;
services.postgresql = {
enable = true;
ensureDatabases = [ "netbox" ];
ensureUsers = [
{
name = "netbox";
ensureDBOwnership = true;
}
];
};
environment.systemPackages = [ netboxManageScript ];
systemd.targets.netbox = {
description = "Target for all NetBox services";
wantedBy = [ "multi-user.target" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" "redis-netbox.service" ];
};
systemd.services = let
defaultServiceConfig = {
WorkingDirectory = "${cfg.dataDir}";
User = "netbox";
Group = "netbox";
StateDirectory = "netbox";
StateDirectoryMode = "0750";
Restart = "on-failure";
RestartSec = 30;
};
in {
netbox = {
description = "NetBox WSGI Service";
documentation = [ "https://docs.netbox.dev/" ];
wantedBy = [ "netbox.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
environment.PYTHONPATH = pkg.pythonPath;
preStart = ''
# On the first run, or on upgrade / downgrade, run migrations and related.
# This mostly correspond to upstream NetBox's 'upgrade.sh' script.
versionFile="${cfg.dataDir}/version"
if [[ -e "$versionFile" && "$(cat "$versionFile")" == "${cfg.package.version}" ]]; then
exit 0
fi
${pkg}/bin/netbox migrate
${pkg}/bin/netbox trace_paths --no-input
${pkg}/bin/netbox collectstatic --no-input
${pkg}/bin/netbox remove_stale_contenttypes --no-input
${pkg}/bin/netbox reindex --lazy
${pkg}/bin/netbox clearsessions
${lib.optionalString
# The clearcache command was removed in 3.7.0:
# https://github.com/netbox-community/netbox/issues/14458
(lib.versionOlder cfg.package.version "3.7.0")
"${pkg}/bin/netbox clearcache"}
echo "${cfg.package.version}" > "$versionFile"
'';
serviceConfig = defaultServiceConfig // {
ExecStart = ''
${pkg.gunicorn}/bin/gunicorn netbox.wsgi \
--bind ${cfg.listenAddress}:${toString cfg.port} \
--pythonpath ${pkg}/opt/netbox/netbox
'';
PrivateTmp = true;
};
};
netbox-rq = {
description = "NetBox Request Queue Worker";
documentation = [ "https://docs.netbox.dev/" ];
wantedBy = [ "netbox.target" ];
after = [ "netbox.service" ];
environment.PYTHONPATH = pkg.pythonPath;
serviceConfig = defaultServiceConfig // {
ExecStart = ''
${pkg}/bin/netbox rqworker high default low
'';
PrivateTmp = true;
};
};
netbox-housekeeping = {
description = "NetBox housekeeping job";
documentation = [ "https://docs.netbox.dev/" ];
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" "netbox.service" ];
wants = [ "network-online.target" ];
environment.PYTHONPATH = pkg.pythonPath;
serviceConfig = defaultServiceConfig // {
Type = "oneshot";
ExecStart = ''
${pkg}/bin/netbox housekeeping
'';
};
};
};
systemd.timers.netbox-housekeeping = {
description = "Run NetBox housekeeping job";
documentation = [ "https://docs.netbox.dev/" ];
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" "netbox.service" ];
wants = [ "network-online.target" ];
timerConfig = {
OnCalendar = "daily";
AccuracySec = "1h";
Persistent = true;
};
};
users.users.netbox = {
home = "${cfg.dataDir}";
isSystemUser = true;
group = "netbox";
};
users.groups.netbox = {};
users.groups."${config.services.redis.servers.netbox.user}".members = [ "netbox" ];
};
}
|