nix-community / terraform-nixos

A set of Terraform modules that are designed to deploy NixOS [maintainer=@adrian-gierakowski]
Apache License 2.0
333 stars 61 forks source link

Consider Terranix Integration #75

Open scottbot95 opened 1 year ago

scottbot95 commented 1 year ago

This would probably be better as a discussion, but discussions weren't enabled on this repo at time of creation

Overview

Terranix is "a NixOS way to create terraform json files." It leverages the NixOS module system to generate a terraform config file.

By providing the utilities in this package as terranix module(s) in addition to (or instead of) the base terraform module, we could potentially simplify the implementation and provide a more flexible interface for consumers of this module.

Pros

Cons

betaboon commented 1 year ago

heya. just wanted to let you know that I'm already using terraform-nixos + terranix for quite a while. that was the initial reason for this terranix PR

here's the snippet of my flake.nix that's relevant:

{
  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-unstable";
    flake-utils.url = "github:numtide/flake-utils";
    terranix = {
      url = "github:terranix/terranix";
      inputs.nixpkgs.follows = "nixpkgs";
      inputs.flake-utils.follows = "flake-utils";
    };
    terraform-nixos = {
      url = "github:tweag/terraform-nixos";
      flake = false;
    };
  };

  outputs = inputs@{ self, ... }:
    let

      inherit (inputs.nixpkgs.lib) nixosSystem;
      inherit (inputs.flake-utils.lib) eachDefaultSystem;
      inherit (inputs.terranix.lib) terranixConfiguration;

    in
    {

      nixosConfigurations.myhost = nixosSystem {
        system = "x86_64-linux";
        specialArgs = { inherit inputs; };
        modules = [
          ./myhost.nix
        ];
      };

      terraformConfigurations.mydeployment = terranixConfiguration {
        system = "x86_64-linux";
        extraArgs = { inherit inputs; };
        modules = [
          ./mydeployment.nix
        ];
      };

    } // (eachDefaultSystem (system:
      let pkgs = import inputs.nixpkgs { inherit system; }; in
      {

        apps.deploy = {
          type = "app";
          program = toString (pkgs.writers.writeBash "deploy" ''
            set -e
            PATH=$PATH:"${pkgs.terraform}/bin"
            WORKSPACE=$(terraform workspace show)
            OUT_LINK=./config.tf.json
            [ -e $OUT_LINK ] && rm -f $OUT_LINK
            nix build --out-link $OUT_LINK .#terraformConfigurations.$WORKSPACE
            terraform init
            terraform apply $@
          '');
        };
      }));
}

and mydeployment.nix:

{ config, pkgs, lib, inputs, ... }:
{

  module."nixos_deploy_myhost" = {
    source = "${inputs.terraform-nixos}/deploy_nixos";
    target_user = "username";
    target_host = "hostname";
    target_port = 2222;
    ssh_agent = true;
    flake = true;
    nixos_config = "myhost";
  };

}