1# Abstractions {#sec-module-abstractions} 2 3If you find yourself repeating yourself over and over, it’s time to abstract. Take, for instance, this Apache HTTP Server configuration: 4 5```nix 6{ 7 services.httpd.virtualHosts = 8 { "blog.example.org" = { 9 documentRoot = "/webroot/blog.example.org"; 10 adminAddr = "alice@example.org"; 11 forceSSL = true; 12 enableACME = true; 13 }; 14 "wiki.example.org" = { 15 documentRoot = "/webroot/wiki.example.org"; 16 adminAddr = "alice@example.org"; 17 forceSSL = true; 18 enableACME = true; 19 }; 20 }; 21} 22``` 23 24It defines two virtual hosts with nearly identical configuration; the only difference is the document root directories. To prevent this duplication, we can use a `let`: 25```nix 26let 27 commonConfig = 28 { adminAddr = "alice@example.org"; 29 forceSSL = true; 30 enableACME = true; 31 }; 32in 33{ 34 services.httpd.virtualHosts = 35 { "blog.example.org" = (commonConfig // { documentRoot = "/webroot/blog.example.org"; }); 36 "wiki.example.org" = (commonConfig // { documentRoot = "/webroot/wiki.example.org"; }); 37 }; 38} 39``` 40 41The `let commonConfig = ...` defines a variable named `commonConfig`. The `//` operator merges two attribute sets, so the configuration of the second virtual host is the set `commonConfig` extended with the document root option. 42 43You can write a `let` wherever an expression is allowed. Thus, you also could have written: 44 45```nix 46{ 47 services.httpd.virtualHosts = 48 let commonConfig = { /* ... */ }; in 49 { "blog.example.org" = (commonConfig // { /* ... */ }); 50 "wiki.example.org" = (commonConfig // { /* ... */ }); 51 }; 52} 53``` 54 55but not `{ let commonConfig = ...; in ...; }` since attributes (as opposed to attribute values) are not expressions. 56 57**Functions** provide another method of abstraction. For instance, suppose that we want to generate lots of different virtual hosts, all with identical configuration except for the document root. This can be done as follows: 58 59```nix 60{ 61 services.httpd.virtualHosts = 62 let 63 makeVirtualHost = webroot: 64 { documentRoot = webroot; 65 adminAddr = "alice@example.org"; 66 forceSSL = true; 67 enableACME = true; 68 }; 69 in 70 { "example.org" = (makeVirtualHost "/webroot/example.org"); 71 "example.com" = (makeVirtualHost "/webroot/example.com"); 72 "example.gov" = (makeVirtualHost "/webroot/example.gov"); 73 "example.nl" = (makeVirtualHost "/webroot/example.nl"); 74 }; 75} 76``` 77 78Here, `makeVirtualHost` is a function that takes a single argument `webroot` and returns the configuration for a virtual host. That function is then called for several names to produce the list of virtual host configurations.