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 =
{ user: File.expand_path('~/.puppetlabs/client-tools/puppetdb.conf'),
global: '/etc/puppetlabs/client-tools/puppetdb.conf',
win_global: 'C:/ProgramData/PuppetLabs/client-tools/puppetdb.conf' }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(config_file, options) ⇒ Config

Returns a new instance of Config.



14
15
16
17
18
19
# File 'lib/bolt/puppetdb/config.rb', line 14

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

Instance Method Details

#[](key) ⇒ Object



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

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

#expand_pathsObject



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

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



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/bolt/puppetdb/config.rb', line 21

def load_config(filename)
  global_path = Bolt::Util.windows? ? DEFAULT_CONFIG[:win_global] : DEFAULT_CONFIG[:global]
  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[:user])
    config = JSON.parse(File.read(DEFAULT_CONFIG[:user]))
  elsif File.exist?(global_path)
    config = JSON.parse(File.read(global_path))
  else
    config = {}
  end
  config.fetch('puppetdb', {})
end

#tokenObject



39
40
41
42
43
44
45
46
# File 'lib/bolt/puppetdb/config.rb', line 39

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



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/bolt/puppetdb/config.rb', line 64

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



58
59
60
61
62
# File 'lib/bolt/puppetdb/config.rb', line 58

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