Skip to content

Instantly share code, notes, and snippets.

@matejc
Last active February 16, 2016 10:42
Show Gist options
  • Save matejc/6092c47f5c1adc596c46 to your computer and use it in GitHub Desktop.
Save matejc/6092c47f5c1adc596c46 to your computer and use it in GitHub Desktop.
Nix2DockerCompose
# run: nix-build ./compose.nix --show-trace && cat ./result
{ pkgs ? import <nixpkgs> {}, file ? ./input.nix }:
let
lib = pkgs.lib;
containers = import file { inherit pkgs; };
prefix = level: str:
let
tabSize = 2;
width = (level * tabSize) + (lib.stringLength str);
in
lib.fixedWidthString width " " str;
path = name: container:
lib.optionals
(builtins.hasAttr name container)
["${prefix 1 name}: ${toString (builtins.getAttr name container)}"];
string = name: container:
lib.optionals
(builtins.hasAttr name container)
["${prefix 1 name}: \"${toString (builtins.getAttr name container)}\""];
list = name: container:
lib.optionals
(builtins.hasAttr name container)
(["${prefix 1 name}:"] ++ (map (entry: prefix 2 "- \"${toString entry}\"") (builtins.getAttr name container)));
containerLines = container:
(lib.mapAttrsToList (n: v:
if lib.isString v then string n container
else if lib.isList v then list n container
else if (builtins.typeOf v) == "path" then path n container
else throw "Attribute with name ${n} has unsupported type (${builtins.typeOf v})!"
) (lib.filterAttrs (n: v: n != "name") container));
lines = map (container:
["${container.name}:"] ++ (containerLines container)
) containers;
output = lib.concatStringsSep "\n" (lib.flatten lines);
in
pkgs.writeText "docker-compose.yml" output
searx:
build: /home/matejc/workarea/searx
enviromnent:
- "MONGODB_URL=mongo://database:27017/db-name"
links:
- "database"
ports:
- "7777:8888"
database:
expose:
- "27017"
image: "mongodb:latest"
# this is just an example, searx does not need any database
{ pkgs }:
let
dbName = "db-name";
in
[
{
name = "searx";
build = /home/matejc/workarea/searx;
ports = [
"7777:8888"
];
enviromnent = [
"MONGODB_URL=mongo://database:27017/${dbName}"
];
links = [
"database"
];
}
{
name = "database";
image = "mongodb:latest";
expose = [
"27017"
];
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment