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, socket_path = nil) ⇒ PostgresSession

Returns a new instance of PostgresSession.



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

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

Instance Method Details

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



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

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 =~ /password authentication failed/ ) && out.downcase =~ /error:/
    raise Inspec::Exceptions::ResourceFailed, "PostgreSQL connection error: #{out}"
  elsif cmd.exit_status != 0 && out.downcase =~ /error:/
    Lines.new(out, "PostgreSQL query with error: #{query}", cmd.exit_status)
  else
    Lines.new(cmd.stdout.strip, "PostgreSQL query: #{query}", cmd.exit_status)
  end
end

#resource_idObject



67
68
69
# File 'lib/inspec/resources/postgres_session.rb', line 67

def resource_id
  "postgress_session:User:#{@user}:Host:#{@host}"
end