Austin Maddox
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Nix Notes High-level Nix notes. ## Videos 2h, Comprehensive "What is Nix": https://youtu.be/6Le0IbPRzOE 28m, Containerization with Nix: https://youtu.be/5XY3K8DH55M 15m, Everything Everywhere all at Once: https://youtu.be/CwfKlX3rA6E [Vimjoyer] 9m, Nix Language Explained: https://youtu.be/UgrwoAGSPOQ 9m, Impermanence Setup: https://youtu.be/YPKwkWtK7l0 7m, NixOS Secrets Management: https://youtu.be/G5f6GC7SnhU ## Links Structured Learning: https://nixos.org/guides/nix-pills/ Discuss: https://discourse.nixos.org/ Awesome-List: https://github.com/nix-community/awesome-nix Wiki: https://nixos.wiki/wiki ISO from Nix: https://nix.dev/tutorials/nixos/building-bootable-iso-image ## RTFM Once you've read and seen enough and want to get going, I recommend using the following repo as a template for your nix configuration files. `grep` for "FIXME" and "TODO" for lines that need your attention and input before rubuilding your os with `sudo nixos-rebuild switch --flake .#hostname`. All of the provided config files have detailed comments regarding features and best practices. Getting Started: - Starter Configs: https://github.com/Misterio77/nix-starter-configs Narrower focus, handy references as you build your OS: Zero to Nix: - https://zero-to-nix.com/start NixOS with Flakes: - https://nixos-and-flakes.thiscute.world/introduction/ How to Upgrade Packages: - https://discourse.nixos.org/t/how-to-upgrade-packages/6151/9 Configure Docker: - https://nixos.wiki/wiki/Docker Configure Zsh: - https://nixos.wiki/wiki/Zsh Configure OpenVPN: - https://nixos.wiki/wiki/OpenVPN NixOS Options (also, don't sleep on the `man` pages): - https://nixos.org/manual/nixos/stable/options.html NixOS Modules: - https://nixos.wiki/wiki/NixOS_modules ## Opinions - [Writing Custom NixOS Modules](https://www.reddit.com/r/NixOS/comments/um1ohu/how_do_you_write_custom_nixos_modules/) ## Nomenclature **derivations** – precise descriptions of how contents of existing files are used to derive new files. ## Why nix? Couldn't say it better myself: https://github.com/hlissner/dotfiles#frequently-asked-questions > Should I use NixOS? > Short answer: no. > Long answer: no really. Don't. > Long long answer: I'm not kidding. Don't. > Unsigned long long answer: Alright alright. Here's why not: > > Its learning curve is steep. > > You will trial and error your way to enlightenment, if you survive long enough. > > NixOS is unlike other Linux distros. Your issues will be unique and difficult to google. > > If the words "declarative", "generational", and "immutable" don't make you fully erect, you're considering NixOS for the wrong reasons. > > The overhead of managing a NixOS config will rarely pay for itself with fewer than 3 systems (perhaps another distro with nix on top would suit you better?). > > Official documentation for Nix(OS) is vast, but shallow. > > Unofficial resources and example configs are sparse and tend to be either too simple or too complex (or outdated). > > The Nix language is obtuse and its toolchain is unintuitive. This is made infinitely worse if you've never touched the shell or a functional language before, but you'll need to learn it to do even a fraction of what makes NixOS worth all the trouble. > > A decent grasp of Linux and its ecosystem is a must, if only to distinguish Nix(OS) issues from Linux (or upstream) issues -- as well as to debug them or report them to the correct authority (and coherently). > > If you need somebody else to tell you whether or not you need NixOS, you don't need NixOS. > > If none of this has deterred you, then you didn't need my advice in the first place. Stop procrastinating and try NixOS! ## What is Nix - About 20MB program written in C++ - An OS - A programming language - A package manager - A method of compiling software from source ### What is Nixpkgs - NixOS/nixpkgs - "Derivations" - Builds from source, 90k+ reproducible recipes ["I installed a library but my compiler is not finding it. Why?"](https://nixos.wiki/wiki/FAQ#I_installed_a_library_but_my_compiler_is_not_finding_it._Why.3F) ### What is NixOS - Built from Nix and Nixpkgs - The result of running `nix build` on the Nix code you've written - Completely declarative ### What are Flakes? ``` WARNING: Since contents of flake files are copied to the world-readable Nix store folder, do not put any unencrypted secrets in flake files. ``` Other users on your machine can see your secrets if you include them in your config. https://www.tweag.io/blog/2020-05-25-flakes/ > A flake is simply a source tree (such as a Git repository) containing a file named flake.nix that provides a standardized interface to Nix artifacts such as packages or NixOS modules. Flakes can have dependencies on other flakes, with a “lock file” pinning those dependencies to exact revisions to ensure reproducible evaluation. I'm thinking that `nix modules` are similar to `terraform` modules, and the `flake` is the implementation, or root module, of one or more modules. ## How do I Handle Secrets? I'm going with `sops-nix`. ### Setup `sops-nix` Example: https://github.com/Mic92/sops-nix#deploy-example Blog on Usage: https://samleathers.com/posts/2022-02-11-my-new-network-and-sops.html #### Generate Keys `mkdir -p ~/.config/sops/age` `nix shell nixpkgs#age -c age-keygen -o ~/.config/sops/age/keys.txt` This will provide a public key. You can review your public key with: `nix shell nixpkgs#age -c age-keygen -y ~/.config/sops/age/keys.txt` Alternatively, you can use your ssh private key to generate the sops key, ensuring the same output should you need to re-generate the key. `nix run nixpkgs#ssh-to-age -- -private-key -i ~/.ssh/private > /.config/sops/age/keys.txt` #### .sops.yaml Somewhere with your nix configs: ``` keys: - &primary <your-public-key> creation_rules: - path_regex: secrets/secrets.yaml$ key_groups: - age: - *primary ``` #### secrets.yaml `sops secrets/secrets.yaml` This will open your default editor to a short template for the secrets file. Your sops `secrets.yaml` can be pushed with the rest of your config since it is encrypted at rest. Make sure you back up your keys. ``` hello: Welcome to SOPS! Edit this file as you please! example_key: example_value # Example comment example_array: - example_value1 - example_value2 example_number: 1234.56789 example_booleans: - true - false ``` Add a secret or two and save, and you'll find encrypted text when you `cat` the file. I use VSCode as my default editor and hit a snag here, circumventing it entirely after attempting a couple of failed workarounds. `vi` or `nano` work fine. `EDITOR=vim sops secrets/secrets.yaml` #### Referencing Secrets w/ Nix Configs [WIP] I'm **[CURRENTLY]** trying, and failing, to use sops-nix for my nix-config secrets. https://github.com/Mic92/sops-nix?tab=readme-ov-file#templates Using the example `secrets.yaml` above, let's reference `example_key` in `configuration.nix`: ``` sops.secrets.example_key = {}; ``` This makes our secret accessible at `/run/secrets/example_key`, owned by `root:root` and readable by the `keys` group. I do not know how to or if you can (or should try to) reference the value of a given variable. I assumed the following would work, but this just points to the secret's filepath. This is fine when the service can read the secret from a file. ``` ... # sops config sops.defaultSopsFile = ../../secrets/secrets.yaml; sops.defaultSopsFormat = "yaml"; sops.age.keyFile = /home/amaddox/.config/sops/age/keys.txt; sops.secrets = { ovpn_pw = {}; }; ... # OpenVPN services.openvpn.servers = { figgVPN = { config = ''config /etc/openvpn/client/client.conf ''; updateResolvConf = true; autoStart = false; authUserPass.password = config.sops.secrets."ovpn_pw".path; authUserPass.username = "amaddox"; }; }; ... ``` `authUserPass.password` is of type `string`. `authUserPass` is a `null` type that could take our file, I think. Docs say that the creds are put in the world-readable Nix store, though. I thought that I might point this to `/run/secrets/ovpn_pw` instead. You can't do this with nix. That file hasn't been generated yet, though I expect it to exist once the system is rebuilt. I need to be able to reference the secret from within the project, so the original value was correct, `config.sops.secrets."ovpn_pw".path`. I needed to update my `ovpn_pw` secret to include the username and update the key name: ``` ovpn_auth: | amaddox D3finiT3ly-MyR3alP@ssw0rd! ``` This shit still doesn't work. ## Services [There are a lot of services](https://search.nixos.org/options?channel=23.11&from=0&size=50&sort=relevance&type=packages&query=services) that can be enabled with just a few lines in your `configuration.nix`. Looking at `openvpn`, above, I've [configured the options](https://search.nixos.org/options?channel=23.11&from=0&size=50&sort=alpha_asc&type=packages&query=services.openvpn) to my linking. I don't want the service to auto-start, since it will prompt me for my MFA during `nixos-rebuild switch` every time. I'd prefer to start/stop this myself. I could configure multiple VPN services but I have only one named "figgVPN", and Nix names this service, `openvpn-figgVPN.service`. If you don't know your service name, look it up with `systemctl list-unit-files | grep -i <service>`. ### Configure Custom Services TODO: Notes on configuring a custom service ## Containerization Example Dockerfile: ```dockerfile FROM ubuntu:jammy RUN apt-get -qq update \ && apt-get -qq install -y --no-install-recommends \ nginx=1.18.0-6ubuntu14.3 I && rm -rf/var/lib/apt/lists/* COPY html/index.html /var/www/html/index.html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` With Nix: ``` { description = "OpenTechLab Docker Example"; inputs = { nixpkgs. url = github:Nix0S/nixpkgs/nixos-22.11; }; outputs = { self, nixpkgs }: { packages. "x86_64-linux" = let pkgs = import nixpkgs { system = "x86_64-linux"; }; in rec { dockerImage = pkgs.dockerTools.buildLayeredImage (let nginxPort = "80"; nginxConf = pkgs.writeText "nginx.conf" '' user nginx nginx; daemon off; events {} http { server { listen ${nginxPort}; location / { root ${./html}; } } } ''; in rec { name = "otl-nix-demo"; } ... ``` Yeah.. It's much longer, but your image will have 0 fat, and byte-for-byte you can reproduce this on any machine at any time. ## Handy Commands `nix repl` is a command-line tool that comes with the Nix package manager. It allows you to interactively explore and evaluate Nix expressions, which are used in Nix configurations. With nix-repl, you can load Nix expressions and see their results in real-time, making it useful for debugging and developing Nix configurations. It provides a read-eval-print loop (REPL) environment where you can enter expressions and view the output, helping you understand how Nix expressions work. `Ctrl+D` to exit. `nix-collect-garbage` is used to clean up the Nix store by identifying and removing unused or outdated items, thereby optimizing disk space usage. `nix-shell -p <package1> <package2` to install packages found at search.nixos.org and drop you into an ephemeral shell with those tools. `--run` will run the command and exit when it has finished, so that you can use commands that aren't installed on your machine. If you want to use "unfree" packages with `nix-env`, `nix-build`, or `nix-shell`; add the following to your `configuration.nix`: ``` mkdir -p ~/.config/nixpkgs && \ echo '{ allowUnfree = true; }' >> ~/.config/nixpkgs/config.nix ``` ## Adding New Hardware I believe the gist for adding new hardware is to plug in and run `nixos-generate-config` again to produce an updated `hardware-configuration.nix`. #### HDD/SSD I added a disk, and had to partition it before getting started, though I'm confident that Nix could probably handle this part as well. Regardless, here's the process: ``` nix-shell -p parted # ID new disk sudo parted -l | grep Error # partition sudo parted /dev/sda mklabel gpt sudo parted -a opt /dev/sda mkpart primary ext4 0% 100% # create filesystem sudo mkfs.ext4 -L datapartition /dev/sda1 # snag uuid sudo lsblk --fs ``` We want the UUID so that we can add it via the `fileSystems` property. ``` ... fileSystems."/media/data" = { device = "/dev/disk/by-uuid/2b13d130-3b5f-4d9d-8bf6-44fs6f44e8ec"; fsType = "ext4"; }; ... ``` I did create `/media/data` before adding this to the config, but I'm sure that Nix would have provisioned it had I not. ## Tips Try this: cd into the directory with your flake.nix run `nix repl` in `nix repl`, type ``:lf .`` (this will load flake.nix into the repl) hit the <tab> key to see possible completions (you should see inputs in there) type `inputs`. and press <tab> and you should see all your inputs For example, I have the Hyprland flake as an input, so I can then type: 6. `inputs.hyprland.` and press <tab> to explore from there. 7. `:?` for help. `:q` to quit the repl This ability to browse around the structure of my flake gave me a better understanding of how it's all laid out. You can also dig into nixosConfigurations to explore your system config, check current value of options etc. Another cool thing you can do with the repl: nix repl '<nixpkgs>' will load nixpkgs directly. Press <tab> and you will see all the packages (well the last few). Start typing the name of an application and then press <tab> to find the package you are looking for. You can explore all the packages using dot notation to see their meta data etc.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully