Hi! Are you tired of writing duplicate Terraform code? Terrafix comes to the rescue! It is a domain-specific language embedded into a purely functional language called Nix (that also powers the NixOS). The goal is to let a Terraform user write concise Nix expressions and translate them into readable Terraform files.
Here’s an example from the project repo. We want to generate variables.tf
for a couple of similar apps. So, we can use Nix functions and make use of a single template for both variables:
let
appPurescript = "app_purescript";
appPython = "app_python";
apps = [ appPurescript appPython ];
# x may have a custom __toString
_mod = x: { _ = "${toString x}"; try = "try_${x}"; path = "path_${x}"; renamed = "renamed_${x}"; };
# we can apply a modifier _mod to consistently use the forms of `app`
dockerVariables = mkVariables (modifyMapMerge apps _mod (app:
{
"${app._}" = {
type = object {
DIR = optional string "/app";
DOCKER_PORT = optional number 80;
HOST = optional string "0.0.0.0";
NAME = optional string "${app.renamed}";
HOST_PORT = number;
};
};
}));
in
This is what we’ll get in variables.tf
:
variable "app_purescript" {
type = object({
DIR = optional(string, "/app")
DOCKER_PORT = optional(number, 80)
HOST = optional(string, "0.0.0.0")
HOST_PORT = number
NAME = optional(string, "renamed_app_purescript")
})
}
variable "app_python" {
type = object({
DIR = optional(string, "/app")
DOCKER_PORT = optional(number, 80)
HOST = optional(string, "0.0.0.0")
HOST_PORT = number
NAME = optional(string, "renamed_app_python")
})
}
In fact, this case can be generalized to any number of apps by extending the apps
list in the Nix code.
Feel interested? Then check the repo to see the rest of this example and get the tools for Terraform file generation!
Bonus: there is even a naive script to convert the existing .tf
files into .nix
ones. See the Tests section of README.
Disclaimer: a lot of Terraform syntax constructs are not yet supported. However, if you leave a couple of issues with the desired features, I’ll be glad to add them!
If you’d like, you may ask questions here or in the Terrafix thread on the NixOS forum.