Class: Bolt::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt/config.rb,
lib/bolt/config/transport/ssh.rb,
lib/bolt/config/transport/base.rb,
lib/bolt/config/transport/orch.rb,
lib/bolt/config/transport/local.rb,
lib/bolt/config/transport/winrm.rb,
lib/bolt/config/transport/docker.rb,
lib/bolt/config/transport/remote.rb

Defined Under Namespace

Modules: Transport

Constant Summary collapse

TRANSPORT_CONFIG =
{
  'ssh'    => Bolt::Config::Transport::SSH,
  'winrm'  => Bolt::Config::Transport::WinRM,
  'pcp'    => Bolt::Config::Transport::Orch,
  'local'  => Bolt::Config::Transport::Local,
  'docker' => Bolt::Config::Transport::Docker,
  'remote' => Bolt::Config::Transport::Remote
}.freeze
OPTIONS =
{
  "apply_settings"           => "A map of Puppet settings to use when applying Puppet code",
  "color"                    => "Whether to use colored output when printing messages to the console.",
  "compile-concurrency"      => "The maximum number of simultaneous manifest block compiles.",
  "concurrency"              => "The number of threads to use when executing on remote targets.",
  "format"                   => "The format to use when printing results. Options are `human` and `json`.",
  "hiera-config"             => "The path to your Hiera config.",
  "inventoryfile"            => "The path to a structured data inventory file used to refer to groups of "\
                                "targets on the command line and from plans.",
  "log"                      => "The configuration of the logfile output. Configuration can be set for "\
                                "`console` and the path to a log file, such as `~/.puppetlabs/bolt/debug.log`.",
  "modulepath"               => "The module path for loading tasks and plan code. This is either an array "\
                                "of directories or a string containing a list of directories separated by the "\
                                "OS-specific PATH separator.",
  "plugin_hooks"             => "Which plugins a specific hook should use.",
  "plugins"                  => "A map of plugins and their configuration data.",
  "puppetdb"                 => "A map containing options for configuring the Bolt PuppetDB client.",
  "puppetfile"               => "A map containing options for the `bolt puppetfile install` command.",
  "save-rerun"               => "Whether to update `.rerun.json` in the Bolt project directory. If "\
                                "your target names include passwords, set this value to `false` to avoid "\
                                "writing passwords to disk.",
  "transport"                => "The default transport to use when the transport for a target is not "\
                                "specified in the URL or inventory.",
  "trusted-external-command" => "The path to an executable on the Bolt controller that can produce "\
                                "external trusted facts. **External trusted facts are experimental in both "\
                                "Puppet and Bolt and this API may change or be removed.**"
}.freeze
DEFAULT_OPTIONS =
{
  "color" => true,
  "concurrency" => 100,
  "compile-concurrency" => "Number of cores",
  "format" => "human",
  "hiera-config" => "Boltdir/hiera.yaml",
  "inventoryfile" => "Boltdir/inventory.yaml",
  "modulepath" => ["Boltdir/modules", "Boltdir/site-modules", "Boltdir/site"],
  "save-rerun" => true
}.freeze
PUPPETFILE_OPTIONS =
{
  "forge" => "A subsection that can have its own `proxy` setting to set an HTTP proxy for Forge operations "\
             "only, and a `baseurl` setting to specify a different Forge host.",
  "proxy" => "The HTTP proxy to use for Git and Forge operations."
}.freeze
LOG_OPTIONS =
{
  "append" => "Add output to an existing log file. Available only for logs output to a "\
              "filepath.",
  "level"  => "The type of information in the log. Either `debug`, `info`, `notice`, "\
              "`warn`, or `error`."
}.freeze
DEFAULT_LOG_OPTIONS =
{
  "append" => true,
  "level"  => "`warn` for console, `notice` for file"
}.freeze
APPLY_SETTINGS =
{
  "show_diff" => "Whether to log and report a contextual diff when files are being replaced. "\
                 "See [Puppet documentation](https://puppet.com/docs/puppet/latest/configuration.html#showdiff) "\
                 "for details"
}.freeze
DEFAULT_APPLY_SETTINGS =
{
  "show_diff" => false
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(boltdir, config_data, overrides = {}) ⇒ Config

Returns a new instance of Config.



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/bolt/config.rb', line 151

def initialize(boltdir, config_data, overrides = {})
  unless config_data.is_a?(Array)
    config_data = [{ filepath: boltdir.config_file, data: config_data }]
  end

  @logger = Logging.logger[self]
  @warnings = []
  @boltdir = boltdir
  @transports = {}
  @config_files = []

  default_data = {
    'apply_settings'      => {},
    'color'               => true,
    'compile-concurrency' => Etc.nprocessors,
    'concurrency'         => 100,
    'format'              => 'human',
    'log'                 => { 'console' => {} },
    'plugin_hooks'        => {},
    'plugins'             => {},
    'puppetdb'            => {},
    'puppetfile'          => {},
    'save-rerun'          => true,
    'transport'           => 'ssh'
  }

  loaded_data = config_data.map do |config|
    @config_files.push(config[:filepath])
    config[:data]
  end

  override_data = normalize_overrides(overrides)

  @data = merge_config_layers(default_data, *loaded_data, override_data)

  TRANSPORT_CONFIG.each do |transport, config|
    @transports[transport] = config.new(@data.delete(transport), @boltdir.path)
  end

  finalize_data
  validate
end

Instance Attribute Details

#boltdirObject (readonly)

Returns the value of attribute boltdir.



26
27
28
# File 'lib/bolt/config.rb', line 26

def boltdir
  @boltdir
end

#config_filesObject (readonly)

Returns the value of attribute config_files.



26
27
28
# File 'lib/bolt/config.rb', line 26

def config_files
  @config_files
end

#dataObject (readonly)

Returns the value of attribute data.



26
27
28
# File 'lib/bolt/config.rb', line 26

def data
  @data
end

#transportsObject (readonly)

Returns the value of attribute transports.



26
27
28
# File 'lib/bolt/config.rb', line 26

def transports
  @transports
end

#warningsObject (readonly)

Returns the value of attribute warnings.



26
27
28
# File 'lib/bolt/config.rb', line 26

def warnings
  @warnings
end

Class Method Details

.defaultObject



104
105
106
# File 'lib/bolt/config.rb', line 104

def self.default
  new(Bolt::Boltdir.new('.'), {})
end

.from_boltdir(boltdir, overrides = {}) ⇒ Object



108
109
110
111
112
113
114
115
116
117
# File 'lib/bolt/config.rb', line 108

def self.from_boltdir(boltdir, overrides = {})
  data = {
    filepath: boltdir.config_file,
    data: Bolt::Util.read_optional_yaml_hash(boltdir.config_file, 'config')
  }

  data = load_defaults.push(data).select { |config| config[:data]&.any? }

  new(boltdir, data, overrides)
end

.from_file(configfile, overrides = {}) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
# File 'lib/bolt/config.rb', line 119

def self.from_file(configfile, overrides = {})
  boltdir = Bolt::Boltdir.new(Pathname.new(configfile).expand_path.dirname)

  data = {
    filepath: boltdir.config_file,
    data: Bolt::Util.read_yaml_hash(configfile, 'config')
  }
  data = load_defaults.push(data).select { |config| config[:data]&.any? }

  new(boltdir, data, overrides)
end

.load_defaultsObject



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/bolt/config.rb', line 131

def self.load_defaults
  # Lazy-load expensive gem code
  require 'win32/dir' if Bolt::Util.windows?

  system_path = if Bolt::Util.windows?
                  Pathname.new(File.join(Dir::COMMON_APPDATA, 'PuppetLabs', 'bolt', 'etc', 'bolt.yaml'))
                else
                  Pathname.new(File.join('/etc', 'puppetlabs', 'bolt', 'bolt.yaml'))
                end
  user_path = begin
                Pathname.new(File.expand_path(File.join('~', '.puppetlabs', 'etc', 'bolt', 'bolt.yaml')))
              rescue ArgumentError
                nil
              end

  confs = [{ filepath: system_path, data: Bolt::Util.read_optional_yaml_hash(system_path, 'config') }]
  confs << { filepath: user_path, data: Bolt::Util.read_optional_yaml_hash(user_path, 'config') } if user_path
  confs
end

Instance Method Details

#apply_settingsObject



430
431
432
# File 'lib/bolt/config.rb', line 430

def apply_settings
  @data['apply_settings']
end

#check_path_case(type, paths) ⇒ Object

Check if there is a case-insensitive match to the path



439
440
441
442
443
444
445
446
447
448
# File 'lib/bolt/config.rb', line 439

def check_path_case(type, paths)
  return if paths.nil?
  matches = matching_paths(paths)

  if matches.any?
    msg = "WARNING: Bolt is case sensitive when specifying a #{type}. Did you mean:\n"
    matches.each { |path| msg += "         #{path}\n" }
    @logger.warn msg
  end
end

#colorObject



398
399
400
# File 'lib/bolt/config.rb', line 398

def color
  @data['color']
end

#compile_concurrencyObject



410
411
412
# File 'lib/bolt/config.rb', line 410

def compile_concurrency
  @data['compile-concurrency']
end

#concurrencyObject



374
375
376
# File 'lib/bolt/config.rb', line 374

def concurrency
  @data['concurrency']
end

#deep_cloneObject



244
245
246
# File 'lib/bolt/config.rb', line 244

def deep_clone
  Bolt::Util.deep_clone(self)
end

#default_inventoryfileObject



350
351
352
# File 'lib/bolt/config.rb', line 350

def default_inventoryfile
  @boltdir.inventory_file
end

#formatObject



378
379
380
# File 'lib/bolt/config.rb', line 378

def format
  @data['format']
end

#format=(value) ⇒ Object



382
383
384
# File 'lib/bolt/config.rb', line 382

def format=(value)
  @data['format'] = value
end

#hiera_configObject



358
359
360
# File 'lib/bolt/config.rb', line 358

def hiera_config
  @data['hiera-config'] || @boltdir.hiera_config
end

#inventoryfileObject



406
407
408
# File 'lib/bolt/config.rb', line 406

def inventoryfile
  @data['inventoryfile']
end

#logObject



390
391
392
# File 'lib/bolt/config.rb', line 390

def log
  @data['log']
end

#matching_paths(paths) ⇒ Object



450
451
452
# File 'lib/bolt/config.rb', line 450

def matching_paths(paths)
  [*paths].map { |p| Dir.glob([p, casefold(p)]) }.flatten.uniq.reject { |p| [*paths].include?(p) }
end

#merge_config_layers(*config_data) ⇒ Object

Merge configuration from all sources into a single hash. Precedence from lowest to highest: defaults, system-wide, user-level, project-level, CLI overrides



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/bolt/config.rb', line 223

def merge_config_layers(*config_data)
  config_data.inject({}) do |acc, config|
    acc.merge(config) do |key, val1, val2|
      case key
      # Plugin config is shallow merged for each plugin
      when 'plugins'
        val1.merge(val2) { |_, v1, v2| v1.merge(v2) }
      # Transports are deep merged
      when *TRANSPORT_CONFIG.keys
        Bolt::Util.deep_merge(val1, val2)
      # Hash values are shallow merged
      when 'puppetdb', 'plugin_hooks', 'apply_settings', 'log'
        val1.merge(val2)
      # All other values are overwritten
      else
        val2
      end
    end
  end
end

#modulepathObject



366
367
368
# File 'lib/bolt/config.rb', line 366

def modulepath
  @data['modulepath'] || @boltdir.modulepath
end

#modulepath=(value) ⇒ Object



370
371
372
# File 'lib/bolt/config.rb', line 370

def modulepath=(value)
  @data['modulepath'] = value
end

#normalize_overrides(options) ⇒ Object

Transforms CLI options into a config hash that can be merged with default and loaded config.



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/bolt/config.rb', line 196

def normalize_overrides(options)
  opts = options.transform_keys(&:to_s)

  # Pull out config options
  overrides = opts.slice(*OPTIONS.keys)

  # Pull out transport config options
  TRANSPORT_CONFIG.each do |transport, config|
    overrides[transport] = opts.slice(*config.options.keys)
  end

  # Set console log to debug if in debug mode
  if options[:debug]
    overrides['log'] = { 'console' => { 'level' => :debug } }
  end

  if options[:puppetfile_path]
    @puppetfile = options[:puppetfile_path]
  end

  overrides['trace'] = opts['trace'] if opts.key?('trace')

  overrides
end

#plugin_hooksObject



422
423
424
# File 'lib/bolt/config.rb', line 422

def plugin_hooks
  @data['plugin_hooks']
end

#pluginsObject



418
419
420
# File 'lib/bolt/config.rb', line 418

def plugins
  @data['plugins']
end

#puppetdbObject



394
395
396
# File 'lib/bolt/config.rb', line 394

def puppetdb
  @data['puppetdb']
end

#puppetfileObject



362
363
364
# File 'lib/bolt/config.rb', line 362

def puppetfile
  @puppetfile || @boltdir.puppetfile
end

#puppetfile_configObject



414
415
416
# File 'lib/bolt/config.rb', line 414

def puppetfile_config
  @data['puppetfile']
end

#rerunfileObject



354
355
356
# File 'lib/bolt/config.rb', line 354

def rerunfile
  @boltdir.rerunfile
end

#save_rerunObject



402
403
404
# File 'lib/bolt/config.rb', line 402

def save_rerun
  @data['save-rerun']
end

#traceObject



386
387
388
# File 'lib/bolt/config.rb', line 386

def trace
  @data['trace']
end

#transportObject



434
435
436
# File 'lib/bolt/config.rb', line 434

def transport
  @data['transport']
end

#trusted_externalObject



426
427
428
# File 'lib/bolt/config.rb', line 426

def trusted_external
  @data['trusted-external-command']
end

#validateObject



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/bolt/config.rb', line 307

def validate
  if @data['future']
    msg = "Configuration option 'future' no longer exposes future behavior."
    @warnings << { option: 'future', msg: msg }
  end

  keys = OPTIONS.keys - %w[plugins plugin_hooks]
  keys.each do |key|
    next unless Bolt::Util.references?(@data[key])
    valid_keys = TRANSPORT_CONFIG.keys + %w[plugins plugin_hooks]
    raise Bolt::ValidationError,
          "Found unsupported key _plugin in config setting #{key}. Plugins are only available in "\
          "#{valid_keys.join(', ')}."
  end

  unless concurrency.is_a?(Integer) && concurrency > 0
    raise Bolt::ValidationError,
          "Concurrency must be a positive Integer, received #{concurrency.class} #{concurrency}"
  end

  unless compile_concurrency.is_a?(Integer) && compile_concurrency > 0
    raise Bolt::ValidationError,
          "Compile concurrency must be a positive Integer, received #{compile_concurrency.class} "\
          "#{compile_concurrency}"
  end

  compile_limit = 2 * Etc.nprocessors
  unless compile_concurrency < compile_limit
    raise Bolt::ValidationError, "Compilation is CPU-intensive, set concurrency less than #{compile_limit}"
  end

  unless %w[human json].include? format
    raise Bolt::ValidationError, "Unsupported format: '#{format}'"
  end

  Bolt::Util.validate_file('hiera-config', @data['hiera_config']) if @data['hiera_config']
  Bolt::Util.validate_file('trusted-external-command', trusted_external) if trusted_external

  unless TRANSPORT_CONFIG.include?(transport)
    raise UnknownTransportError, transport
  end
end