Assign password to postgres user declaratively

I’m creating PostgreSQL user declaratively, using services.postgresql.ensureUsers, but due to security reasons, I need this user to be authenticated with password. I have looked through Postgres module inside Nixpkgs repo(nixpkgs/postgresql.nix at f155651d3f137d802d6b0a94bcb331a6ad0f00a6 · NixOS/nixpkgs · GitHub), but haven’t found any configuration options, related to password.

So, I’m wondering, is there’s any way to define password to postgresql user declaratively?

You could use initialScript I suppose. Not a great idea, though. Creating databases and database users isn’t reproducible… so you probably shouldn’t rely too heavily on these options for production environments.

1 Like

I am not sure how great of an idea this is, but it has been working for me for awhile.

Basically I just reset the password on every postgresql start by adding to the systemd service’s postStart. Here is an example of reading the password from a file using agenix.

  # Set the authentik postgresql password
  systemd.services.postgresql.postStart = let
    password_file_path = config.age.secrets.service_authentik_postgres_password.path;
  in ''
    $PSQL -tA <<'EOF'
      DO $$
      DECLARE password TEXT;
      BEGIN
        password := trim(both from replace(pg_read_file('${password_file_path}'), E'\n', '''));
        EXECUTE format('ALTER ROLE authentik WITH PASSWORD '''%s''';', password);
      END $$;
    EOF
  '';

EDIT: Just saw the date of the original post, sorry for the necro.

2 Likes