Class: Bolt::PuppetDB::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt/puppetdb/config.rb

Constant Summary collapse

DEFAULT_TOKEN =
File.expand_path('~/.puppetlabs/token')
DEFAULT_CONFIG =
File.expand_path('~/.puppetlabs/client-tools/puppetdb.conf')

Instance Method Summary collapse

Constructor Details

#initialize(config_file, options) ⇒ Config

Returns a new instance of Config.



11
12
13
14
15
16
17
# File 'lib/bolt/puppetdb/config.rb', line 11

def initialize(config_file, options)
  @settings = load_config(config_file)
  @settings.merge!(options)

  expand_paths
  validate
end

Instance Method Details

#[](key) ⇒ Object



43
44
45
# File 'lib/bolt/puppetdb/config.rb', line 43

def [](key)
  @settings[key]
end

#expand_pathsObject



47
48
49
50
51
# File 'lib/bolt/puppetdb/config.rb', line 47

def expand_paths
  %w[cacert cert key token].each do |file|
    @settings[file] = File.expand_path(@settings[file]) if @settings[file]
  end
end

#load_config(filename) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/bolt/puppetdb/config.rb', line 19

def load_config(filename)
  if filename
    if File.exist?(filename)
      config = JSON.parse(File.read(filename))
    else
      raise Bolt::PuppetDBError, "config file #{filename} does not exist"
    end
  elsif File.exist?(DEFAULT_CONFIG)
    config = JSON.parse(File.read(DEFAULT_CONFIG))
  else
    config = {}
  end
  config.fetch('puppetdb', {})
end

#tokenObject



34
35
36
37
38
39
40
41
# File 'lib/bolt/puppetdb/config.rb', line 34

def token
  return @token if @token
  if @settings['token']
    File.read(@settings['token'])
  elsif File.exist?(DEFAULT_TOKEN)
    File.read(DEFAULT_TOKEN)
  end
end

#validateObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/bolt/puppetdb/config.rb', line 59

def validate
  unless @settings['server_urls']
    raise Bolt::PuppetDBError, "server_urls must be specified"
  end
  unless @settings['cacert']
    raise Bolt::PuppetDBError, "cacert must be specified"
  end

  if (@settings['cert'] && !@settings['key']) ||
     (!@settings['cert'] && @settings['key'])
    raise Bolt::PuppetDBError, "cert and key must be specified together"
  end

  validate_file_exists('cacert')
  validate_file_exists('cert')
  validate_file_exists('key')
end

#validate_file_exists(file) ⇒ Object



53
54
55
56
57
# File 'lib/bolt/puppetdb/config.rb', line 53

def validate_file_exists(file)
  if @settings[file] && !File.exist?(@settings[file])
    raise Bolt::PuppetDBError, "#{file} file #{@settings[file]} does not exist"
  end
end