Class: Inspec::Resources::PostgresSession

Inherits:
Object
  • Object
show all
Defined in:
lib/inspec/resources/postgres_session.rb

Instance Method Summary collapse

Constructor Details

#initialize(user, pass, host = nil, port = nil) ⇒ PostgresSession

Returns a new instance of PostgresSession.



43
44
45
46
47
48
49
50
51
# File 'lib/inspec/resources/postgres_session.rb', line 43

def initialize(user, pass, host = nil, port = nil)
  @user = user || "postgres"
  @pass = pass
  @host = host || "localhost"
  @port = port || 5432
  raise Inspec::Exceptions::ResourceFailed, "Can't run PostgreSQL SQL checks without authentication." if @user.nil? || @pass.nil?

  test_connection
end

Instance Method Details

#query(query, db = []) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/inspec/resources/postgres_session.rb', line 53

def query(query, db = [])
  raise Inspec::Exceptions::ResourceFailed, "#{resource_exception_message}" if resource_failed?

  psql_cmd = create_psql_cmd(query, db)
  cmd = inspec.command(psql_cmd, redact_regex: %r{(:\/\/[a-z]*:).*(@)})
  out = cmd.stdout + "\n" + cmd.stderr
  if cmd.exit_status != 0 || out =~ /could not connect to .*/ || out.downcase =~ /^error:.*/
    raise Inspec::Exceptions::ResourceFailed, "PostgreSQL query with errors: #{out}"
  else
    Lines.new(cmd.stdout.strip, "PostgreSQL query: #{query}")
  end
end