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.



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

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

  expand_paths
  validate
end

Instance Method Details

#[](key) ⇒ Object



41
42
43
# File 'lib/bolt/puppetdb/config.rb', line 41

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

#expand_pathsObject



45
46
47
48
49
# File 'lib/bolt/puppetdb/config.rb', line 45

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



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

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



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

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



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

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



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

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