### OpNix Example Template Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/README.md A template for creating new OpNix configuration examples. It includes sections for description, prerequisites, configuration, validation, troubleshooting, and related examples. ```markdown # Service Name Configuration Brief description of what this example demonstrates. ## Prerequisites - List of requirements - Specific versions if needed - External dependencies ## Configuration ### 1Password Setup Instructions for setting up items in 1Password. ### NixOS Configuration Complete Nix configuration with explanations. ### Validation Steps to verify the configuration works. ## Troubleshooting Common issues and solutions specific to this example. ## Related Examples Links to related configurations. ``` -------------------------------- ### Opnix DevShell Setup and Usage Source: https://context7.com/brizzbuzz/opnix/llms.txt Provides commands for one-time setup of Opnix token file and entering the development shell. It also shows how to skip secret resolution for offline or CI use. ```bash # One-time setup mkdir -p ~/.config/opnix opnix token -path ~/.config/opnix/token set export OPNIX_ENV_TOKEN_FILE=$HOME/.config/opnix/token # Enter the devshell — secrets are injected automatically nix develop # INFO: Resolving OpNix environment secrets... # → export API_TOKEN='...' # → export DB_URL='...' # → export APP_ENV='development' # WARNING: Skipped optional env var OPTIONAL_SECRET: ... # Skip resolution for offline / CI use OPNIX_ENV_DISABLE=1 nix develop ``` -------------------------------- ### Systemd Integration Example Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Enable and configure advanced systemd integration for managing secrets, including change detection and error handling. ```nix services.onepassword-secrets.systemdIntegration = { enable = true; services = ["caddy" "postgresql"]; restartOnChange = true; changeDetection.enable = true; errorHandling.rollbackOnFailure = true; }; ``` -------------------------------- ### Nix Path Behavior Example Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Demonstrates how OpNix handles explicit paths versus inferred paths based on variable names. ```nix # Old format sslCert = { reference = "op://Vault/SSL/certificate"; path = "/etc/ssl/certs/app.pem"; # Explicit path }; # New format - same behavior sslCert = { reference = "op://Vault/SSL/certificate"; path = "/etc/ssl/certs/app.pem"; # Same explicit path }; ``` ```nix # This creates a file at: /var/lib/opnix/secrets/databasePassword databasePassword = { reference = "op://Vault/Database/password"; }; ``` -------------------------------- ### Add OpNix Using Nix Channels Source: https://github.com/brizzbuzz/opnix/blob/main/docs/README.md Install OpNix by adding its tarball to your Nix channels. ```bash nix-channel --add https://github.com/brizzbuzz/opnix/archive/main.tar.gz opnix nix-channel --update ``` -------------------------------- ### Recommended OpNix Token Setup Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/devshell-env.md Set up the OpNix token securely. This involves creating a directory, setting the token, setting permissions, and exporting the token file path for use. ```bash mkdir -p ~/.config/opnix opnix token -path ~/.config/opnix/token set chmod 600 ~/.config/opnix/token export OPNIX_ENV_TOKEN_FILE=$HOME/.config/opnix/token # Add the export to your shell profile or .envrc for convenience ``` -------------------------------- ### Configure Custom Token File Path Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Example of how to specify a custom path for the OpNix token file within your Nix configuration. ```nix services.onepassword-secrets = { tokenFile = "/custom/path/to/token"; # Check this path }; ``` -------------------------------- ### Path Template Example Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Define a template for generating secret paths, allowing variable substitution for service, environment, and name. ```nix pathTemplate = "/etc/secrets/{service}/{environment}/{name}"; ``` -------------------------------- ### Manually Test OpNix Service Start Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Manually start and check the status of the OpNix systemd service. This is useful for isolating issues related to service startup. ```bash sudo systemctl start opnix-secrets.service ``` ```bash sudo systemctl status opnix-secrets.service ``` -------------------------------- ### CI/CD Integration with GitHub Actions Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md Example GitHub Actions workflow to test OpNix configuration using Nix flake commands. ```yaml name: OpNix Configuration Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: cachix/install-nix-action@v22 - name: Test configuration run: | nix flake check nix build .#nixosConfigurations.test.config.system.build.toplevel ``` -------------------------------- ### Basic Home Manager Setup with OpNix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/basic-home-manager.md Enables OpNix for Home Manager to manage secrets. Configure SSH, Git, and GitHub CLI to utilize these managed secrets. Ensures necessary directories exist for secret storage. ```nix { config, pkgs, ... }: { # Enable OpNix for Home Manager programs.onepassword-secrets = { enable = true; tokenFile = "/etc/opnix-token"; # System token (requires group membership) secrets = { # SSH private key sshPrivateKey = { reference = "op://Personal/SSH-Key-Main/private-key"; path = ".ssh/id_rsa"; mode = "0600"; }; # SSH public key sshPublicKey = { reference = "op://Personal/SSH-Key-Main/public-key"; path = ".ssh/id_rsa.pub"; mode = "0644"; }; # GitHub API token githubToken = { reference = "op://Personal/Development-API-Keys/github-token"; path = ".config/gh/token"; mode = "0600"; }; # GPG private key gpgPrivateKey = { reference = "op://Personal/Development-Config/gpg-key"; path = ".gnupg/private-key.asc"; mode = "0600"; }; # NPM configuration npmConfig = { reference = "op://Personal/Development-Config/npmrc"; path = ".npmrc"; mode = "0600"; }; }; }; # Configure SSH with the managed key programs.ssh = { enable = true; # SSH will automatically use ~/.ssh/id_rsa extraConfig = '' # Use OpNix-managed SSH key IdentityFile ~/.ssh/id_rsa # GitHub configuration Host github.com HostName github.com User git IdentityFile ~/.ssh/id_rsa IdentitiesOnly yes ''; # SSH agent configuration startAgent = true; }; # Configure Git with signing key programs.git = { enable = true; userName = "Your Name"; userEmail = "your.email@example.com"; # Git signing configuration will reference the GPG key extraConfig = { commit = { gpgsign = true; }; user = { signingkey = "your-gpg-key-id"; # Replace with actual key ID }; }; }; # Configure GitHub CLI programs.gh = { enable = true; # GitHub CLI will use the token from ~/.config/gh/token }; # Ensure necessary directories exist home.file = { ".ssh/.keep".text = ""; ".config/gh/.keep".text = ""; ".gnupg/.keep".text = ""; }; } ``` -------------------------------- ### Manage Database Credentials with Opnix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/getting-started.md Configure database credentials, such as PostgreSQL passwords, using Opnix. This example shows how to reference the secret and use it to set the initial password for the PostgreSQL user. ```nix services.onepassword-secrets.secrets = { postgresPassword = { reference = "op://Homelab/Database/password"; owner = "postgres"; group = "postgres"; services = ["postgresql"]; }; }; # Reference the secret in your PostgreSQL config services.postgresql = { enable = true; authentication = "local all all trust"; initialScript = pkgs.writeText "init.sql" '' ALTER USER postgres PASSWORD '$(cat ${config.services.onepassword-secrets.secretPaths.postgresPassword})'; ''; }; ``` -------------------------------- ### Configure User-Specific Token File (Nix) Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Specify a custom location for the 1Password token file within your Home Manager configuration. This is useful for user-specific setups. ```nix programs.onepassword-secrets = { tokenFile = "${config.home.homeDirectory}/.config/opnix/token"; }; ``` -------------------------------- ### Enable Systemd Integration for Secrets Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Configure OpNix to integrate with systemd, ensuring services start only after secrets are available. Specify which services should be managed. ```nix services.onepassword-secrets.systemdIntegration = { enable = true; services = ["caddy" "postgresql"]; }; ``` -------------------------------- ### Check SSH Key File Format Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/basic-home-manager.md Verify the format of your SSH private key file. Ensure it starts with the correct header. ```bash file ~/.ssh/id_rsa ``` ```bash head -1 ~/.ssh/id_rsa # Should start with "-----BEGIN" ``` -------------------------------- ### Optimize OpNix Configuration Files Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Consolidate secrets into fewer configuration files to potentially improve retrieval performance. This example shows using a single JSON file for all secrets. ```nix # Group related secrets in single config files services.onepassword-secrets = { configFiles = [ ./all-secrets.json ]; # Better than many small files }; ``` -------------------------------- ### Enable Systemd Integration for Service Dependencies Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Ensures services wait for secrets to be available before starting. Specify dependent services. ```nix services.onepassword-secrets.systemdIntegration = { enable = true; services = ["postgresql" "caddy"]; # These will wait for secrets }; ``` -------------------------------- ### User-Specific Token Setup for OpNix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/basic-home-manager.md Configures OpNix to use a user-specific token file located in the user's home directory. This is an alternative to using a system-wide token. ```nix { config, pkgs, ... }: { programs.onepassword-secrets = { enable = true; # Use user-specific token tokenFile = "${config.home.homeDirectory}/.config/opnix/token"; secrets = { sshPrivateKey = { reference = "op://Personal/SSH-Key-Main/private-key"; path = ".ssh/id_rsa"; mode = "0600"; }; # Add more secrets as needed }; }; # Create token directory home.file.".config/opnix/.keep".text = ""; } ``` -------------------------------- ### Check PostgreSQL SSL Configuration Settings Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/postgresql.md Query PostgreSQL to confirm if SSL is enabled and to retrieve the paths to the SSL certificate and key files. This is useful for verifying SSL setup. ```bash sudo -u postgres psql -c "SHOW ssl;" sudo -u postgres psql -c "SHOW ssl_cert_file;" ``` -------------------------------- ### Check PostgreSQL Service Logs Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/postgresql.md View the system journal logs for the PostgreSQL service to diagnose startup failures. This command helps in identifying issues preventing the database from starting. ```bash sudo journalctl -u postgresql.service ``` -------------------------------- ### Integrate OpNix Environment Configuration into Flake Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/devshell-env.md Wire the OpNix environment configuration into your flake's devshell definition. This example shows how to import and use the configuration within the flake. ```nix { description = "Example devshell with OpNix env integration"; inputs = { nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; opnix.url = "github:brizzbuzz/opnix"; }; outputs = { self, nixpkgs, opnix, ... }: let system = "x86_64-linux"; pkgs = import nixpkgs { inherit system; }; buildOpnix = opnix.packages.${system}.default; opnixEnvConfig = { vars = [ { name = "API_TOKEN"; reference = "op://Homelab/API/token"; } { name = "LOCAL_DB_PASSWORD"; reference = "op://Homelab/Database/password"; optional = true; } ]; }; opnixEnvTokenFile = let tokenPath = builtins.getEnv "OPNIX_ENV_TOKEN_FILE"; in if tokenPath == "" then null else tokenPath; in { devShells.${system}.default = import ./nix/devshell.nix { inherit pkgs buildOpnix; inherit opnixEnvConfig; opnixEnvTokenFile = opnixEnvTokenFile; }; }; } ``` -------------------------------- ### Configure API Keys for Services with Opnix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/getting-started.md Manage API keys for services like Grafana using Opnix. This example demonstrates referencing a secret key and configuring Grafana to use it. ```nix services.onepassword-secrets.secrets = { grafanaSecretKey = { reference = "op://Homelab/Grafana/secret-key"; owner = "grafana"; group = "grafana"; services = ["grafana"]; }; }; services.grafana = { enable = true; settings.security.secret_key = "$__file{${config.services.onepassword-secrets.secretPaths.grafanaSecretKey}}"; }; ``` -------------------------------- ### 1Password Reference Examples Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Illustrates the format for 1Password references, which include VaultName, ItemName, and FieldName. Examples cover different types of secrets. ```plaintext op://Homelab/Database/password ``` ```plaintext op://Personal/SSH-Keys/private-key ``` ```plaintext op://Work/API-Tokens/github-token ``` -------------------------------- ### Set Up OpNix Token and Rebuild Source: https://github.com/brizzbuzz/opnix/blob/main/docs/README.md After configuring OpNix, set up the necessary token using the `opnix token set` command and then rebuild your NixOS system to apply the changes. ```bash sudo opnix token set sudo nixos-rebuild switch --flake . ``` -------------------------------- ### Set Up Token for Devshell Usage Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Recommended workflow for setting up a token file for OpNix devshell usage. This involves creating a directory, setting the token, and exporting the token file path. ```bash mkdir -p ~/.config/opnix opnix token -path ~/.config/opnix/token set chmod 600 ~/.config/opnix/token export OPNIX_ENV_TOKEN_FILE=$HOME/.config/opnix/token # or add the export to your shell profile/direnv ``` -------------------------------- ### Home Manager Config Files Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Provide a list of JSON configuration files for Home Manager's OpNix integration. ```nix configFiles = [./personal-secrets.json ./work-secrets.json]; ``` -------------------------------- ### OpNix Log Patterns Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Examples of successful operation, warning, and error messages found in OpNix logs. ```log INFO: Starting OpNix secret deployment INFO: Processing 3 secrets INFO: Successfully deployed all secrets ``` ```log WARNING: Token file /etc/opnix-token does not exist! INFO: Using existing secrets, skipping updates ``` ```log ERROR: Authentication failed ERROR: Cannot write secret file ERROR: 1Password reference not found ``` -------------------------------- ### Check OpNix Service Timing Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Inspect the start and exit timestamps of the OpNix secrets service to understand its operational duration. ```bash # Check service timing systemctl show opnix-secrets.service -p ExecMainStartTimestamp -p ExecMainExitTimestamp ``` -------------------------------- ### Boot from Rescue Media Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md In case of boot failures suspected to be related to OpNix, boot from a rescue media or a previous NixOS generation. ```bash # At GRUB menu, select previous generation # Or boot from NixOS installation media ``` -------------------------------- ### Graceful Degradation with Missing Tokens Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Demonstrates V1's behavior when the token file is missing, preventing boot failures and providing informative messages. ```bash # V1 handles missing tokens gracefully WARNING: Token file /etc/opnix-token does not exist! INFO: Using existing secrets, skipping updates INFO: Run 'opnix token set' to configure the token ``` -------------------------------- ### Set Up and Verify Token File Permissions (Bash) Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md After setting the OpNix token, ensure it has proper file permissions (640) and ownership (root:onepassword-secrets) for enhanced security. Verify these permissions using `ls -la`. ```bash # Set up token with proper permissions sudo opnix token set sudo chmod 640 /etc/opnix-token sudo chown root:onepassword-secrets /etc/opnix-token # Verify permissions ls -la /etc/opnix-token # Should show: -rw-r----- 1 root onepassword-secrets ``` -------------------------------- ### OpNix Error Message Example Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Illustrates the error message OpNix displays when invalid secret key names (non-camelCase) are used. ```text error: Invalid secret key names. OpNix requires camelCase variable names like 'databasePassword', not path-like strings. Invalid keys: "database/password", "ssl/cert" ``` -------------------------------- ### Enter Development Environment with Nix Source: https://github.com/brizzbuzz/opnix/blob/main/AGENTS.md Use this command to enter the Nix development shell for the project. This ensures all dependencies are correctly set up. ```bash nix develop ``` -------------------------------- ### Set Up and Secure User Token Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Manually set up a user-specific 1Password token file. Ensure the token file has restricted permissions (0600) for security. ```bash mkdir -p ~/.config/opnix opnix token set -path ~/.config/opnix/token chmod 600 ~/.config/opnix/token ``` -------------------------------- ### Configure PostgreSQL with 1Password Secrets and Backups Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/postgresql.md This Nix configuration enables PostgreSQL, integrates 1Password for managing sensitive credentials (admin password, backup user password, S3 credentials), and sets up a daily backup service. The backup service dumps the database, uploads it to S3, and cleans up old local backups. ```nix { config, pkgs, ... }: { services.onepassword-secrets = { enable = true; tokenFile = "/etc/opnix-token"; secrets = { # PostgreSQL admin password postgresAdminPassword = { reference = "op://Homelab/PostgreSQL-Admin/password"; owner = "postgres"; group = "postgres"; mode = "0600"; services = ["postgresql"]; }; # Backup user password postgresBackupPassword = { reference = "op://Homelab/PostgreSQL-Backup/password"; owner = "postgres"; group = "postgres"; mode = "0600"; services = ["postgresql"]; }; # S3 credentials for backups backupS3Credentials = { reference = "op://Homelab/Backup-S3/credentials"; path = "/etc/postgresql/s3-credentials"; owner = "postgres"; group = "postgres"; mode = "0600"; services = ["postgresql-backup"]; }; }; }; services.postgresql = { enable = true; package = pkgs.postgresql_15; initialScript = pkgs.writeText "postgres-backup-init.sql" '' -- Set admin password ALTER USER postgres PASSWORD '$(cat ${config.services.onepassword-secrets.secretPaths."postgres/admin-password"})'; -- Create backup user CREATE USER backup_user WITH PASSWORD '$(cat ${config.services.onepassword-secrets.secretPaths."postgres/backup-password"})'; -- Grant backup privileges GRANT SELECT ON ALL TABLES IN SCHEMA public TO backup_user; GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO backup_user; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO backup_user; ''; settings = { # Enable WAL archiving for continuous backup wal_level = "replica"; archive_mode = true; archive_command = "/usr/local/bin/archive-wal.sh %f %p"; max_wal_senders = 3; wal_keep_segments = 64; }; }; # Backup service systemd.services.postgresql-backup = { description = "PostgreSQL Database Backup"; serviceConfig = { Type = "oneshot"; User = "postgres"; Group = "postgres"; ExecStart = pkgs.writeScript "postgres-backup" '' #!/bin/bash set -euo pipefail # Load S3 credentials source ${config.services.onepassword-secrets.secretPaths."backup/s3-credentials"} # Set backup parameters BACKUP_DATE=$(date +%Y%m%d_%H%M%S) BACKUP_DIR="/var/backups/postgresql" BACKUP_FILE="$BACKUP_DIR/backup_$BACKUP_DATE.sql.gz" # Ensure backup directory exists mkdir -p "$BACKUP_DIR" # Create database backup echo "Creating PostgreSQL backup..." PGPASSWORD="$(cat ${config.services.onepassword-secrets.secretPaths."postgres/backup-password"})" \ pg_dumpall -h localhost -U backup_user | gzip > "$BACKUP_FILE" # Upload to S3 (assuming aws-cli is configured with credentials) echo "Uploading backup to S3..." aws s3 cp "$BACKUP_FILE" "s3://my-backups/postgresql/" --storage-class GLACIER # Clean up local backups older than 7 days find "$BACKUP_DIR" -name "backup_*.sql.gz" -mtime +7 -delete echo "Backup completed successfully" ''; }; after = [ "postgresql.service" "opnix-secrets.service" ]; wants = [ "postgresql.service" ]; }; # Schedule daily backups systemd.timers.postgresql-backup = { description = "PostgreSQL Backup Timer"; wantedBy = [ "timers.target" ]; timerConfig = { OnCalendar = "daily"; Persistent = true; RandomizedDelaySec = "1h"; }; }; # Create backup directory systemd.tmpfiles.rules = [ "d /var/backups/postgresql 0755 postgres postgres -" ]; } ``` -------------------------------- ### Display OpNix Service Definition Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md View the systemd service definition for OpNix secrets management. This helps in understanding how the service is configured and started. ```bash systemctl cat opnix-secrets.service ``` -------------------------------- ### Proper Service Ordering with OpNix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Demonstrates the correct approach to service ordering by making services that require secrets depend on 'opnix-secrets.service', rather than the other way around. ```nix # Instead, make services depend on OpNix: services.onepassword-secrets.systemdIntegration = { enable = true; services = ["postgresql"]; }; ``` -------------------------------- ### Check OpNix Group Membership Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Verify the existence of the `onepassword-secrets` group and check if the current user is a member. This is crucial for Home Manager setups. ```bash getent group onepassword-secrets groups $(whoami) ``` -------------------------------- ### Build Packaged Binary with Nix Source: https://github.com/brizzbuzz/opnix/blob/main/AGENTS.md Produce the packaged Opnix binary using Nix. This command builds the project according to its Nix definitions. ```bash nix build .#opnix ``` -------------------------------- ### Limit OpNix Memory Usage Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Configure systemd to limit the maximum memory the OpNix secrets service can use. This example sets a limit of 100MB. ```nix systemd.services.opnix-secrets = { serviceConfig = { MemoryMax = "100M"; }; }; ``` -------------------------------- ### Home Manager Configuration Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Basic structure for configuring OpNix integration within Home Manager. ```nix programs.onepassword-secrets = { # ... options }; ``` -------------------------------- ### Manually Define Service Dependencies on OpNix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Manually configure systemd service units to depend on the 'opnix-secrets.service'. This ensures secrets are ready before the service starts. ```nix systemd.services.caddy = { after = [ "opnix-secrets.service" ]; wants = [ "opnix-secrets.service" ]; }; ``` -------------------------------- ### Run Go Test Suite Source: https://github.com/brizzbuzz/opnix/blob/main/AGENTS.md Execute the Go test suite for all packages. Use the -count=1 flag to ensure tests are run fresh without caching. ```bash go test ./... ``` ```bash go test ./... -count=1 ``` -------------------------------- ### Verify PostgreSQL Role Exists Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/postgresql.md Check if the 'postgres' role exists in the PostgreSQL database. This is a preliminary step to ensure basic database user setup is correct. ```bash sudo -u postgres psql -c "SELECT rolname FROM pg_roles WHERE rolname = 'postgres';" ``` -------------------------------- ### Global Systemd Service Dependencies Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Enables global systemd integration to ensure specified services wait for secrets to be deployed before starting. Can also configure restarts on change. ```nix services.onepassword-secrets.systemdIntegration = { enable = true; services = ["caddy" "postgresql" "grafana"]; restartOnChange = true; }; ``` -------------------------------- ### Test OpNix Configuration Syntax Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Evaluates the OpNix service configuration syntax using nix-instantiate to catch errors early. ```bash # Test configuration syntax nix-instantiate --eval --strict -E ' with import {}; (import ./configuration.nix { inherit pkgs; }).services.onepassword-secrets ' ``` -------------------------------- ### Build Go CLI Source: https://github.com/brizzbuzz/opnix/blob/main/AGENTS.md Build the Opnix CLI executable using Go. This command compiles the Go source files into a binary. ```bash go build ./cmd/opnix ``` -------------------------------- ### Test OpNix Configuration with Nix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Commands to build, test, and check the status of the OpNix service during migration. ```bash # Build configuration without applying nix build .#nixosConfigurations.yourhostname.config.system.build.toplevel # Test the configuration sudo nixos-rebuild test --flake . # Check OpNix service status sudo systemctl status opnix-secrets.service # Verify secrets are accessible ls -la /var/lib/opnix/secrets/ ``` -------------------------------- ### Inspect OpNix launchd Service Details Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Get detailed information about the OpNix launchd service, including its configuration and current state. This is helpful for diagnosing launchd-related problems. ```bash sudo launchctl list org.nixos.opnix-secrets ``` ```bash sudo launchctl print system/org.nixos.opnix-secrets ``` -------------------------------- ### Configure OpNix Backup Strategies Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md Define backup strategies for OpNix configuration, specifying primary and emergency fallback configurations. Document emergency procedures for accessing credentials and switching accounts. ```nix # Backup strategy for OpNix configuration services.onepassword-secrets = { # Primary configuration configFiles = [ ./secrets/prod.json ]; # Emergency fallback configuration # configFiles = [ ./secrets/emergency.json ]; }; # Document emergency procedures: # 1. How to access emergency credentials # 2. How to switch to backup 1Password account # 3. How to restore from configuration backups ``` -------------------------------- ### Configure PostgreSQL with SSL and Secrets Management Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/postgresql.md This Nix configuration enables the PostgreSQL service, sets up SSL encryption using certificates managed by onepassword-secrets, and configures authentication methods. It also includes network and performance settings. ```nix { config, pkgs, ... }: { services.onepassword-secrets = { enable = true; tokenFile = "/etc/opnix-token"; secrets = { # PostgreSQL superuser password postgresSuperuserPassword = { reference = "op://Homelab/PostgreSQL-Main/superuser-password"; owner = "postgres"; group = "postgres"; mode = "0600"; services = ["postgresql"]; }; # SSL certificate for PostgreSQL postgresSslCert = { reference = "op://Homelab/PostgreSQL-SSL/certificate"; path = "/var/lib/postgresql/server.crt"; owner = "postgres"; group = "postgres"; mode = "0600"; services = ["postgresql"]; }; # SSL private key for PostgreSQL postgresSslKey = { reference = "op://Homelab/PostgreSQL-SSL/private-key"; path = "/var/lib/postgresql/server.key"; owner = "postgres"; group = "postgres"; mode = "0600"; services = ["postgresql"]; }; # SSL CA certificate postgresCaCert = { reference = "op://Homelab/PostgreSQL-SSL/ca-certificate"; path = "/var/lib/postgresql/ca.crt"; owner = "postgres"; group = "postgres"; mode = "0644"; services = ["postgresql"]; }; }; }; services.postgresql = { enable = true; package = pkgs.postgresql_15; # SSL-enabled authentication authentication = '' # SSL connections hostssl all all 0.0.0.0/0 md5 hostssl all all ::/0 md5 # Local connections local all all peer ''; settings = { # SSL Configuration ssl = true; ssl_cert_file = config.services.onepassword-secrets.secretPaths."postgres/ssl-cert"; ssl_key_file = config.services.onepassword-secrets.secretPaths."postgres/ssl-key"; ssl_ca_file = config.services.onepassword-secrets.secretPaths."postgres/ca-cert"; ssl_ciphers = "HIGH:MEDIUM:+3DES:!aNULL"; ssl_prefer_server_ciphers = true; # Network settings listen_addresses = "*"; port = 5432; max_connections = 100; # Security settings password_encryption = "scram-sha-256"; # Performance settings shared_buffers = "256MB"; effective_cache_size = "1GB"; }; }; # Firewall configuration for SSL connections networking.firewall = { allowedTCPPorts = [ 5432 ]; }; } ``` -------------------------------- ### Troubleshooting: Certificate Not Loading Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/caddy-ssl.md Steps to resolve Caddy reporting a certificate file not found error, including checking service status, file paths, and permissions. ```bash # Check OpNix service status sudo systemctl status opnix-secrets.service # Verify file paths in configuration match actual files sudo ls -la /etc/ssl/certs/ sudo ls -la /etc/ssl/private/ # Check file permissions sudo ls -la /etc/ssl/certs/example.com.pem # Should show: -rw-r--r-- 1 caddy caddy ``` -------------------------------- ### Configure 1Password Token File (NixOS/nix-darwin) Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Specify the path to the file containing the 1Password service account token. The file should only contain the token and have recommended permissions of `640`. ```nix services.onepassword-secrets = { enable = true; tokenFile = "/etc/opnix-token"; }; ``` -------------------------------- ### Multi-Service JSON Configuration for Secrets Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/README.md A JSON configuration to manage multiple secrets for different services, including path, reference, owner, group, and mode. Useful for complex setups involving multiple applications. ```json { "secrets": [ { "path": "caddy/ssl-cert", "reference": "op://Homelab/SSL/certificate", "owner": "caddy", "group": "caddy", "mode": "0644" }, { "path": "postgres/password", "reference": "op://Homelab/Database/password", "owner": "postgres", "group": "postgres", "mode": "0600" } ] } ``` -------------------------------- ### Check Home Manager Activation Output Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Run Home Manager with verbose output to identify errors during system activation. ```bash home-manager switch --verbose ``` -------------------------------- ### Configure 1Password Secrets Source: https://github.com/brizzbuzz/opnix/blob/main/README.md Enable and configure 1Password secrets integration within your NixOS, nix-darwin, or Home Manager setup. Specify the token file for system-wide secrets or define user-specific secrets with paths and modes. ```nix # NixOS/nix-darwin services.onepassword-secrets = { enable = true; tokenFile = "/etc/opnix-token"; secrets = { databasePassword = { reference = "op://Homelab/Database/password"; owner = "postgres"; services = ["postgresql"]; }; }; }; # Home Manager programs.onepassword-secrets = { enable = true; secrets = { sshPrivateKey = { reference = "op://Personal/SSH/private-key"; path = ".ssh/id_rsa"; mode = "0600"; }; }; }; ``` -------------------------------- ### Configure OpNix for Development Environment Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md Conditionally enable OpNix and configure token files based on the environment (development vs. production). Use development-specific secrets with fake or test data for the development environment. ```nix # Separate development configuration services.onepassword-secrets = { enable = lib.mkIf (!config.environment.isDevelopment) true; tokenFile = if config.environment.isDevelopment then "/etc/opnix-dev-token" else "/etc/opnix-prod-token"; secrets = lib.mkIf config.environment.isDevelopment { # Development secrets with fake/test data databasePassword = { reference = "op://Dev-Vault/Test-DB/password"; }; }; }; ``` -------------------------------- ### Initialize 1Password Client and Get Token Source: https://context7.com/brizzbuzz/opnix/llms.txt Constructs a 1Password SDK client using a token file or the OP_SERVICE_ACCOUNT_TOKEN environment variable. GetToken prioritizes the environment variable over the file. The client's ResolveSecret method can then resolve 'op://' references. ```go package main import ( "fmt" "log" "github.com/brizzbuzz/opnix/internal/onepass" ) func main() { // GetToken: env var OP_SERVICE_ACCOUNT_TOKEN wins over file token, err := onepass.GetToken("/etc/opnix-token") if err != nil { log.Fatalf("token error: %v", err) } fmt.Println("token length:", len(token)) // NewClient wraps the 1Password SDK client, err := onepass.NewClient("/etc/opnix-token") if err != nil { log.Fatalf("client error: %v", err) // structured OpnixError with suggestions } // ResolveSecret fetches a single field value value, err := client.ResolveSecret("op://Homelab/Database/password") if err != nil { log.Fatalf("resolve error: %v", err) } fmt.Println("secret:", value) } ``` -------------------------------- ### Optimize Service Dependencies with Systemd Integration Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md Enable systemd integration for OpNix secrets to optimize service startup by specifying only essential dependent services. This prevents circular dependencies. ```nix services.onepassword-secrets.systemdIntegration = { enable = true; services = ["caddy" "postgresql"]; # Only essential services restartOnChange = true; }; ``` -------------------------------- ### Basic Caddy SSL Configuration with OpNix Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/caddy-ssl.md This Nix configuration enables OpNix to manage SSL certificates for Caddy. It sets up secrets for the certificate and private key, enables systemd integration for automatic restarts, and configures Caddy virtual hosts to use these certificates. Ensure necessary directories and firewall rules are in place. ```nix { config, pkgs, ... }: { # Enable OpNix with SSL certificate management services.onepassword-secrets = { enable = true; tokenFile = "/etc/opnix-token"; secrets = { # SSL Certificate sslExampleComCert = { reference = "op://Homelab/SSL-Certificate-Example-Com/certificate"; path = "/etc/ssl/certs/example.com.pem"; owner = "caddy"; group = "caddy"; mode = "0644"; # Certificate can be world-readable services = ["caddy"]; }; # SSL Private Key sslExampleComKey = { reference = "op://Homelab/SSL-Certificate-Example-Com/private-key"; path = "/etc/ssl/private/example.com.key"; owner = "caddy"; group = "caddy"; mode = "0600"; # Private key must be restricted services = ["caddy"]; }; }; # Enable advanced systemd integration systemdIntegration = { enable = true; services = ["caddy"]; restartOnChange = true; changeDetection.enable = true; }; }; # Configure Caddy web server services.caddy = { enable = true; # Caddy configuration using OpNix-managed certificates virtualHosts."example.com" = { extraConfig = '' # Use certificates managed by OpNix tls ${config.services.onepassword-secrets.secretPaths.sslExampleComCert} ${config.services.onepassword-secrets.secretPaths.sslExampleComKey} # Your site configuration root * /var/www/example.com file_server # Optional: Add security headers header { # Security headers Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" X-Content-Type-Options "nosniff" X-Frame-Options "DENY" X-XSS-Protection "1; mode=block" Referrer-Policy "strict-origin-when-cross-origin" } # Optional: Enable gzip compression encode gzip # Optional: Access logging log { output file /var/log/caddy/example.com.access.log format single_field common_log } ''; }; }; # Create necessary directories systemd.tmpfiles.rules = [ "d /etc/ssl/certs 0755 root root -" "d /etc/ssl/private 0700 root root -" "d /var/www/example.com 0755 caddy caddy -" "d /var/log/caddy 0755 caddy caddy -" ]; # Configure firewall networking.firewall = { allowedTCPPorts = [ 80 443 ]; }; } ``` -------------------------------- ### Accessing Secret Paths in Home Manager Configuration Source: https://github.com/brizzbuzz/opnix/blob/main/docs/configuration-reference.md Shows how to use generated secret paths within Home Manager configurations, exemplified by configuring Git's user signing key. ```nix # Access secret paths in Home Manager programs.git = { enable = true; extraConfig = { user = { signingkey = builtins.readFile config.programs.onepassword-secrets.secretPaths.gitSigningKey; }; }; }; ``` -------------------------------- ### Keep Existing V0 Configuration in V1 Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Your existing V0 configuration using `configFile` will continue to work in V1, providing immediate access to V1's reliability improvements without any changes. ```nix # Your existing V0 configuration continues to work services.onepassword-secrets = { enable = true; configFile = ./secrets.json; users = ["alice" "bob"]; tokenFile = "/etc/opnix-token"; outputDir = "/var/lib/opnix/secrets"; }; ``` -------------------------------- ### Troubleshooting: Certificate Permission Denied Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/caddy-ssl.md Commands to fix Caddy's inability to read certificate files by correcting ownership and permissions. ```bash # Fix ownership sudo chown caddy:caddy /etc/ssl/certs/example.com.pem sudo chown caddy:caddy /etc/ssl/private/example.com.key # Fix permissions sudo chmod 644 /etc/ssl/certs/example.com.pem sudo chmod 600 /etc/ssl/private/example.com.key ``` -------------------------------- ### Add OpNix Systemd Service Integration Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Demonstrates how to enable and configure systemd service integration for OpNix secrets. ```nix # Before: No service integration services.onepassword-secrets = { enable = true; configFile = ./secrets.json; }; # After: With service integration services.onepassword-secrets = { enable = true; configFile = ./secrets.json; # Keep existing # Add service integration systemdIntegration = { enable = true; services = ["caddy" "postgresql"]; restartOnChange = true; }; }; ``` -------------------------------- ### Constructing and Wrapping Opnix Errors Source: https://context7.com/brizzbuzz/opnix/llms.txt Demonstrates how to construct a specific Opnix error using a dedicated constructor (TokenError) and how to wrap an existing error with additional suggestions using WrapWithSuggestions. It also shows how to unwrap the error using errors.As. ```go package main import ( "errors" "fmt" opnixerrors "github.com/brizzbuzz/opnix/internal/errors" ) func main() { // Construct a structured error err := opnixerrors.TokenError( "Token file does not exist", "/etc/opnix-token", nil, ) fmt.Println(err) // ERROR: Token access failed in authentication // Issue: Token file does not exist // Context: Token file: /etc/opnix-token // // Suggestions: // 1. Set up your 1Password service account token: // 2. 1. Visit https://my.1password.com/developer-tools/infrastructure-secrets // 3. 3. Copy the token and run: opnix token set // 4. 4. Or manually create file: echo 'your-token' | sudo tee /etc/opnix-token // Wrap an existing error and add suggestions cause := fmt.Errorf("connection refused") wrapped := opnixerrors.WrapWithSuggestions( cause, "Connecting to 1Password API", "network", []string{ "Check internet connectivity", "Verify firewall rules allow outbound HTTPS", }, ) // Unwrap works with the standard errors package var opErr *opnixerrors.OpnixError if errors.As(wrapped, &opErr) { fmt.Println("operation:", opErr.Operation) // Connecting to 1Password API fmt.Println("component:", opErr.Component) // network fmt.Println("cause:", opErr.Cause) // connection refused } } ``` -------------------------------- ### Full Migration to V1 Declarative Configuration Source: https://github.com/brizzbuzz/opnix/blob/main/docs/migration-guide.md Leverage all V1 features by defining all secrets declaratively, including custom owners, modes, and systemd service integrations for automatic restarts. ```nix services.onepassword-secrets = { enable = true; tokenFile = "/etc/opnix-token"; # All secrets defined declaratively secrets = { databasePassword = { reference = "op://Homelab/PostgreSQL/password"; owner = "postgres"; group = "postgres"; mode = "0600"; services = ["postgresql"]; }; sslCertificate = { reference = "op://Homelab/SSL/certificate"; path = "/etc/ssl/certs/app.pem"; owner = "caddy"; group = "caddy"; mode = "0644"; services = { caddy = { restart = true; after = ["opnix-secrets.service"]; }; }; }; }; # Enable advanced features systemdIntegration = { enable = true; services = ["caddy" "postgresql"]; restartOnChange = true; changeDetection.enable = true; }; }; ``` -------------------------------- ### Set OpNix Token and Rebuild System Source: https://github.com/brizzbuzz/opnix/blob/main/README.md After configuring OpNix, set your 1Password token using the `opnix token set` command and then rebuild your system configuration to apply the changes. ```bash sudo opnix token set sudo nixos-rebuild switch --flake . ``` -------------------------------- ### Check OpNix Service Integration Dependencies Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md Examine the 'After' dependencies for OpNix secrets and Caddy services, and test service restart behavior. ```bash # Check service dependencies systemctl show opnix-secrets.service -p After systemctl show caddy.service -p After ``` ```bash # Verify service restart behavior systemctl restart opnix-secrets.service systemctl status caddy.service ``` -------------------------------- ### Test OpNix Configuration Changes Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md Test OpNix configuration changes by building the system configuration and reviewing changes before applying them. Use `nixos-rebuild test` for staging environments. ```bash # Test configuration changes nix build .#nixosConfigurations.hostname.config.system.build.toplevel # Review changes before applying # Test in staging environment first nixos-rebuild test --flake .#staging-server ``` -------------------------------- ### Apply Home Manager Configuration Source: https://github.com/brizzbuzz/opnix/blob/main/docs/examples/basic-home-manager.md Apply the Home Manager configuration to deploy secrets and settings. Verify that secrets have been deployed to their expected locations. ```bash # Apply the configuration home-manager switch # Verify secrets are deployed ls -la ~/.ssh/ ls -la ~/.config/tokens/ ls -la ~/.npmrc ``` -------------------------------- ### Add OpNix Without Flakes Source: https://github.com/brizzbuzz/opnix/blob/main/docs/README.md Import OpNix into your configuration without using Nix Flakes by fetching the tarball. ```nix let opnix = builtins.fetchTarball { url = "https://github.com/brizzbuzz/opnix/archive/main.tar.gz"; }; in { imports = [ "${opnix}/nix/module.nix" ]; } ``` -------------------------------- ### Verify OpNix Secrets Configuration Source: https://github.com/brizzbuzz/opnix/blob/main/docs/troubleshooting.md Ensure the configuration for deploying 1Password secrets to the home directory is correct. The 'path' is relative to the user's home directory. ```nix programs.onepassword-secrets.secrets.sshKey = { reference = "op://Personal/SSH/key"; path = ".ssh/id_rsa"; # Relative to home directory }; ``` -------------------------------- ### Troubleshoot OpNix Network Issues Source: https://github.com/brizzbuzz/opnix/blob/main/docs/best-practices.md Test connectivity to 1Password services, check DNS resolution, and verify account/vault access using the 1Password CLI. ```bash # Test connectivity to 1Password curl -I https://my.1password.com/api/v1/ping ``` ```bash # Check DNS resolution nslookup my.1password.com ``` ```bash # Test with 1Password CLI op account list op vault list ```