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 =

NOTE: All configuration options should have a corresponding schema property

in schemas/bolt-config.schema.json
{
  "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(project, config_data, overrides = {}) ⇒ Config

Returns a new instance of Config.



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
193
194
# File 'lib/bolt/config.rb', line 153

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

  @logger = Logging.logger[self]
  @warnings = []
  @project = project
  @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), @project.path)
  end

  finalize_data
  validate
end

Instance Attribute Details

#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

#projectObject (readonly)

Returns the value of attribute project.



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

def project
  @project
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



106
107
108
# File 'lib/bolt/config.rb', line 106

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

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



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

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

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

  new(project, data, overrides)
end

.from_project(project, overrides = {}) ⇒ Object



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

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

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

  new(project, data, overrides)
end

.load_defaultsObject



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

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



432
433
434
# File 'lib/bolt/config.rb', line 432

def apply_settings
  @data['apply_settings']
end

#check_path_case(type, paths) ⇒ Object

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



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

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



400
401
402
# File 'lib/bolt/config.rb', line 400

def color
  @data['color']
end

#compile_concurrencyObject



412
413
414
# File 'lib/bolt/config.rb', line 412

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

#concurrencyObject



376
377
378
# File 'lib/bolt/config.rb', line 376

def concurrency
  @data['concurrency']
end

#deep_cloneObject



246
247
248
# File 'lib/bolt/config.rb', line 246

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

#default_inventoryfileObject



352
353
354
# File 'lib/bolt/config.rb', line 352

def default_inventoryfile
  @project.inventory_file
end

#formatObject



380
381
382
# File 'lib/bolt/config.rb', line 380

def format
  @data['format']
end

#format=(value) ⇒ Object



384
385
386
# File 'lib/bolt/config.rb', line 384

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

#hiera_configObject



360
361
362
# File 'lib/bolt/config.rb', line 360

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

#inventoryfileObject



408
409
410
# File 'lib/bolt/config.rb', line 408

def inventoryfile
  @data['inventoryfile']
end

#logObject



392
393
394
# File 'lib/bolt/config.rb', line 392

def log
  @data['log']
end

#matching_paths(paths) ⇒ Object



452
453
454
# File 'lib/bolt/config.rb', line 452

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



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

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



368
369
370
# File 'lib/bolt/config.rb', line 368

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

#modulepath=(value) ⇒ Object



372
373
374
# File 'lib/bolt/config.rb', line 372

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.



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

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



424
425
426
# File 'lib/bolt/config.rb', line 424

def plugin_hooks
  @data['plugin_hooks']
end

#pluginsObject



420
421
422
# File 'lib/bolt/config.rb', line 420

def plugins
  @data['plugins']
end

#puppetdbObject



396
397
398
# File 'lib/bolt/config.rb', line 396

def puppetdb
  @data['puppetdb']
end

#puppetfileObject



364
365
366
# File 'lib/bolt/config.rb', line 364

def puppetfile
  @puppetfile || @project.puppetfile
end

#puppetfile_configObject



416
417
418
# File 'lib/bolt/config.rb', line 416

def puppetfile_config
  @data['puppetfile']
end

#rerunfileObject



356
357
358
# File 'lib/bolt/config.rb', line 356

def rerunfile
  @project.rerunfile
end

#save_rerunObject



404
405
406
# File 'lib/bolt/config.rb', line 404

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

#traceObject



388
389
390
# File 'lib/bolt/config.rb', line 388

def trace
  @data['trace']
end

#transportObject



436
437
438
# File 'lib/bolt/config.rb', line 436

def transport
  @data['transport']
end

#trusted_externalObject



428
429
430
# File 'lib/bolt/config.rb', line 428

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

#validateObject



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
349
350
# File 'lib/bolt/config.rb', line 309

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