Rails: fe_sendauth: no password supplied (PG::ConnectionBad) from Ruby, but ok in Rails

gnoll110 picture gnoll110 · Dec 22, 2015 · Viewed 10.5k times · Source

I'm having problems assessing a postgres database from straight ruby.

I've created a Postgres database using Rails

>rails new www --database=postgresql

using Rails 4.2.5 and Postgres is 9.4

It produces the following config/database.yml file.

default: &default
  adapter: postgresql
  encoding: unicode
  pool: 5

development:
  <<: *default
  database: www_development

test:
  <<: *default
  database: www_test

production:
  <<: *default
  database: www_production
  username: www
  password: <%= ENV['WWW_DATABASE_PASSWORD'] %>

I can run rails server, db:drop, db:create and db:migrate fine.

I can also access the database fine with psql

>psql www_development

But when I run the following app.rb from a non Rails project directory, I get a fe_sendauth: no password supplied (PG::ConnectionBad) error message.

It's clearly not a Rails issue. I've either missed something in my ruby or Postgres need a tweek to handle some difference between Rails and pure Ruby [that I'm not aware off]. I've also included Postgres' pg_hba.conf file.

At wits end trying to figure this one out. Any help would be much appreciated.

app.rb

require 'yaml'
require 'active_record'
require 'pg'

ActiveRecord::Base.establish_connection(
  adapter:  'postgresql',
  host:     'localhost',
  database: 'www_development',
)

/etc/postgresql/9.4/main/pg_hba.conf

# TYPE  DATABASE        USER            ADDRESS                 METHOD

local   all             postgres                                peer
local   all             all                                     peer
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5

Answer

Kasperi picture Kasperi · May 17, 2017

With ENV variable as password it's very likely that the variable itself is not present. Confirm the presence with printenv. You need to relogin/reboot for the variable to be accessible after you've included it in /etc/environment file for example. If this works, it's probably better than changing pg_hba.conf.