Class: Bolt::Application

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

Instance Method Summary collapse

Constructor Details

#initialize(analytics:, config:, executor:, inventory:, pal:, plugins:) ⇒ Application

Returns a new instance of Application.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/bolt/application.rb', line 13

def initialize(
  analytics:,
  config:,
  executor:,
  inventory:,
  pal:,
  plugins:
)
  @analytics = analytics
  @config    = config
  @executor  = executor
  @inventory = inventory
  @logger    = Bolt::Logger.logger(self)
  @pal       = pal
  @plugins   = plugins
end

Instance Method Details

#add_module(name, outputter) ⇒ Boolean

Add a new module to the project.

Parameters:

  • name (String)

    The name of the module to add.

  • outputter (Bolt::Outputter)

    An outputter instance.

Returns:

  • (Boolean)


251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/bolt/application.rb', line 251

def add_module(name, outputter)
  assert_project_file(config.project)

  installer = Bolt::ModuleInstaller.new(outputter, pal)

  installer.add(name,
                config.project.modules,
                config.project.puppetfile,
                config.project.managed_moduledir,
                config.project.project_file,
                @plugins.resolve_references(config.module_install))
end

#apply(manifest, targets, code: '', noop: false) ⇒ Bolt::ResultSet

Apply Puppet manifest code to a list of targets.

Parameters:

  • manifest (String, NilClass)

    The path to a Puppet manifest file.

  • targets (Array[String])

    The targets to run on.

  • code (String) (defaults to: '')

    Puppet manifest code to apply.

  • noop (Boolean) (defaults to: false)

    Whether to apply in no-operation mode.

Returns:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/bolt/application.rb', line 44

def apply(manifest, targets, code: '', noop: false)
  manifest_code = if manifest
                    Bolt::Util.validate_file('manifest', manifest)
                    File.read(File.expand_path(manifest))
                  else
                    code
                  end

  targets = inventory.get_targets(targets)

  Puppet[:tasks] = false
  ast = pal.parse_manifest(manifest_code, manifest)

  if defined?(ast.body) &&
     (ast.body.is_a?(Puppet::Pops::Model::HostClassDefinition) ||
     ast.body.is_a?(Puppet::Pops::Model::ResourceTypeDefinition))
    message = "Manifest only contains definitions and will result in no changes on the targets. "\
              "Definitions must be declared for their resources to be applied. You can read more "\
              "about defining and declaring classes and types in the Puppet documentation at "\
              "https://puppet.com/docs/puppet/latest/lang_classes.html and "\
              "https://puppet.com/docs/puppet/latest/lang_defined_types.html"
    Bolt::Logger.warn("empty_manifest", message)
  end

  # Apply logging looks like plan logging
  executor.publish_event(type: :plan_start, plan: nil)

  with_benchmark do
    apply_prep_results = pal.in_plan_compiler(executor, inventory, plugins.puppetdb_client) do |compiler|
      compiler.call_function('apply_prep', targets, '_catch_errors' => true)
    end

    apply_results = pal.with_bolt_executor(executor, inventory, plugins.puppetdb_client) do
      Puppet.lookup(:apply_executor)
            .apply_ast(ast, apply_prep_results.ok_set.targets, catch_errors: true, noop: noop)
    end

    Bolt::ResultSet.new(apply_prep_results.error_set.results + apply_results.results)
  end
end

#convert_plan(plan) ⇒ String

Convert a YAML plan to a Puppet language plan.

Parameters:

  • plan (String)

    The plan to convert. Can be a plan name or a path.

Returns:

  • (String)

    The converted plan.



322
323
324
# File 'lib/bolt/application.rb', line 322

def convert_plan(plan)
  pal.convert_plan(plan)
end

#create_project(name, outputter, modules: nil) ⇒ Boolean

Initialize the current directory as a Bolt project.

Parameters:

  • name (String)

    The name of the project.

  • An (Bolt::Outputter)

    outputter instance.

  • modules (Array[String], NilClass) (defaults to: nil)

    Modules to install.

Returns:

  • (Boolean)


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

def create_project(name, outputter, modules: nil)
  Bolt::ProjectManager.new(config, outputter, pal)
                      .create(Dir.pwd, name, modules)
end

#create_secret_keys(force: false, plugin: 'pkcs7') ⇒ Boolean

Generate a keypair using the configured secret plugin.

Parameters:

  • force (Boolean) (defaults to: false)

    Forcibly create a keypair.

  • plugin (String) (defaults to: 'pkcs7')

    The secret plugin to use.

Returns:

  • (Boolean)


461
462
463
464
465
466
467
468
# File 'lib/bolt/application.rb', line 461

def create_secret_keys(force: false, plugin: 'pkcs7')
  unless plugins.by_name(plugin)
    raise Bolt::Plugin::PluginError::Unknown, plugin
  end

  plugins.get_hook(plugin, :secret_createkeys)
         .call('force' => force)
end

#decrypt_secret(ciphertext, plugin: 'pkcs7') ⇒ Boolean

Decrypt ciphertext using the configured secret plugin.

Parameters:

  • ciphertext (String)

    The ciphertext to decrypt.

  • plugin (String) (defaults to: 'pkcs7')

    The secret plugin to use.

Returns:

  • (Boolean)


476
477
478
479
480
481
482
483
# File 'lib/bolt/application.rb', line 476

def decrypt_secret(ciphertext, plugin: 'pkcs7')
  unless plugins.by_name(plugin)
    raise Bolt::Plugin::PluginError::Unknown, plugin
  end

  plugins.get_hook(plugin, :secret_decrypt)
         .call('encrypted_value' => ciphertext)
end

#download_file(source, destination, targets) ⇒ Bolt::ResultSet

Download a file from a list of targets to a directory on the controller.

Parameters:

  • source (String)

    The path to the file on the targets.

  • destination (String)

    The path to the directory on the controller.

  • targets (Array[String])

    The targets to run on.

Returns:



107
108
109
110
111
112
113
114
# File 'lib/bolt/application.rb', line 107

def download_file(source, destination, targets)
  destination = File.expand_path(destination, Dir.pwd)
  targets     = inventory.get_targets(targets)

  with_benchmark do
    executor.download_file(targets, source, destination)
  end
end

#encrypt_secret(plaintext, plugin: 'pkcs7') ⇒ Boolean

Encrypt plaintext using the configured secret plugin.

Parameters:

  • plaintext (String)

    The plaintext to encrypt.

  • plugin (String) (defaults to: 'pkcs7')

    The secret plugin to use.

Returns:

  • (Boolean)


491
492
493
494
495
496
497
498
# File 'lib/bolt/application.rb', line 491

def encrypt_secret(plaintext, plugin: 'pkcs7')
  unless plugins.by_name(plugin)
    raise Bolt::Plugin::PluginError::Unknown, plugin
  end

  plugins.get_hook(plugin, :secret_encrypt)
         .call('plaintext_value' => plaintext)
end

#generate_typesBoolean

Generate Puppet data types from project modules.

Returns:

  • (Boolean)


268
269
270
# File 'lib/bolt/application.rb', line 268

def generate_types
  pal.generate_types(cache: true)
end

#install_modules(outputter, force: false, resolve: true) ⇒ Boolean

Install the project’s modules.

Parameters:

  • outputter (Bolt::Outputter)

    An outputter instance.

  • force (Boolean) (defaults to: false)

    Forcibly install modules.

  • resolve (Boolean) (defaults to: true)

    Resolve module dependencies.

Returns:

  • (Boolean)


279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/bolt/application.rb', line 279

def install_modules(outputter, force: false, resolve: true)
  assert_project_file(config.project)

  if config.project.modules.empty? && resolve
    outputter.print_message(
      "Project configuration file #{config.project.project_file} does not "\
      "specify any module dependencies. Nothing to do."
    )
    return true
  end

  installer = Bolt::ModuleInstaller.new(outputter, pal)

  installer.install(config.project.modules,
                    config.project.puppetfile,
                    config.project.managed_moduledir,
                    @plugins.resolve_references(config.module_install),
                    force: force,
                    resolve: resolve)
end

#list_groupsHash

Show groups in the inventory.

Returns:

  • (Hash)


138
139
140
141
142
143
144
145
146
147
# File 'lib/bolt/application.rb', line 138

def list_groups
  {
    count: inventory.group_names.count,
    groups: inventory.group_names.sort,
    inventory: {
      default: config.default_inventoryfile.to_s,
      source: inventory.source
    }
  }
end

#list_guidesBoolean

Show available guides.

Parameters:

  • guides (Hash)

    A map of topics to paths to guides.

  • outputter (Bolt::Outputter)

    An outputter instance.

Returns:

  • (Boolean)


155
156
157
# File 'lib/bolt/application.rb', line 155

def list_guides
  { topics: load_guides.keys }
end

#list_modulesHash

Show modules available to the project.

Returns:

  • (Hash)

    A map of module directories to module definitions.



304
305
306
# File 'lib/bolt/application.rb', line 304

def list_modules
  pal.list_modules
end

#list_plans(filter: nil) ⇒ Hash

List plans available to the project.

Parameters:

  • filter (String) (defaults to: nil)

    A substring to filter plans by.

Returns:

  • (Hash)


401
402
403
404
405
406
# File 'lib/bolt/application.rb', line 401

def list_plans(filter: nil)
  {
    plans:      filter_content(pal.list_plans_with_cache(filter_content: true), filter),
    modulepath: pal.user_modulepath
  }
end

#list_pluginsHash

Show available plugins.

Returns:

  • (Hash)


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

def list_plugins
  { plugins: plugins.list_plugins, modulepath: pal.user_modulepath }
end

#list_tasks(filter: nil) ⇒ Hash

List available tasks.

Parameters:

  • filter (String) (defaults to: nil)

    A substring to filter tasks by.

Returns:

  • (Hash)


528
529
530
531
532
533
# File 'lib/bolt/application.rb', line 528

def list_tasks(filter: nil)
  {
    tasks:      filter_content(pal.list_tasks_with_cache(filter_content: true), filter),
    modulepath: pal.user_modulepath
  }
end

#lookup(key, targets, vars: {}) ⇒ Bolt::ResultSet, String

Lookup a value with Hiera.

Parameters:

  • key (String)

    The key to look up in the hierarchy.

  • targets (Array[String])

    The targets to use as context.

  • vars (Hash) (defaults to: {})

    Variables to set in the scope.

Returns:



223
224
225
226
227
228
229
230
231
232
233
# File 'lib/bolt/application.rb', line 223

def lookup(key, targets, vars: {})
  executor.publish_event(type: :plan_start, plan: nil)

  with_benchmark do
    pal.lookup(key,
               inventory.get_targets(targets),
               inventory,
               executor,
               plan_vars: vars)
  end
end

#migrate_project(outputter) ⇒ Boolean

Migrate a project to current best practices.

Parameters:

Returns:

  • (Boolean)


433
434
435
# File 'lib/bolt/application.rb', line 433

def migrate_project(outputter)
  Bolt::ProjectManager.new(config, outputter, pal).migrate
end

#new_plan(name, puppet: false, plan_script: nil) ⇒ Boolean

Create a new project-level plan.

Parameters:

  • name (String)

    The name of the new plan.

  • puppet (Boolean) (defaults to: false)

    Create a Puppet language plan.

  • plan_script (String) (defaults to: nil)

    Reference to the script to run in the new plan.

Returns:

  • (Boolean)


333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/bolt/application.rb', line 333

def new_plan(name, puppet: false, plan_script: nil)
  Bolt::PlanCreator.validate_plan_name(config.project, name)

  if plan_script
    Bolt::Util.validate_file('script', find_file(plan_script))
  end

  Bolt::PlanCreator.create_plan(config.project.plans_path,
                                name,
                                is_puppet: puppet,
                                script: plan_script)
end

#plan_lookup(key, vars: {}) ⇒ String

Lookup a value with Hiera using plan_hierarchy.

Parameters:

  • key (String)

    The key to lookup up in the plan_hierarchy.

  • vars (Hash) (defaults to: {})

    Variables to set in the scope.

Returns:

  • (String)

    The result of the lookup.



241
242
243
# File 'lib/bolt/application.rb', line 241

def plan_lookup(key, vars: {})
  pal.plan_hierarchy_lookup(key, plan_vars: vars)
end

#run_command(command, targets, env_vars: nil) ⇒ Bolt::ResultSet

Run a command on a list of targets.

Parameters:

  • command (String)

    The command.

  • targets (Array[String])

    The targets to run on.

  • env_vars (Hash) (defaults to: nil)

    Environment variables to set on the target.

Returns:



92
93
94
95
96
97
98
# File 'lib/bolt/application.rb', line 92

def run_command(command, targets, env_vars: nil)
  targets = inventory.get_targets(targets)

  with_benchmark do
    executor.run_command(targets, command, env_vars: env_vars)
  end
end

#run_plan(plan, targets, params: {}) ⇒ Bolt::PlanResult

Run a plan.

Parameters:

  • plan (String)

    The plan to run.

  • targets (Array[String], NilClass)

    The targets to pass to the plan.

  • params (Hash) (defaults to: {})

    Parameters to pass to the plan.

Returns:



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/bolt/application.rb', line 353

def run_plan(plan, targets, params: {})
  if targets && targets.any?
    if params['nodes'] || params['targets']
      key = params.include?('nodes') ? 'nodes' : 'targets'
      raise Bolt::CLIError,
            "A plan's '#{key}' parameter can be specified using the --#{key} option, but in that " \
            "case it must not be specified as a separate #{key}=<value> parameter nor included " \
            "in the JSON data passed in the --params option"
    end

    plan_params  = pal.get_plan_info(plan)['parameters']
    target_param = plan_params.dig('targets', 'type') =~ /TargetSpec/
    node_param   = plan_params.include?('nodes')

    if node_param && target_param
      msg = "Plan parameters include both 'nodes' and 'targets' with type 'TargetSpec', " \
            "neither will populated with the value for --nodes or --targets."
      Bolt::Logger.warn("nodes_targets_parameters", msg)
    elsif node_param
      params['nodes'] = targets.join(',')
    elsif target_param
      params['targets'] = targets.join(',')
    end
  end

  plan_context = { plan_name: plan, params: params }

  executor.start_plan(plan_context)
  result = pal.run_plan(plan, params, executor, inventory, plugins.puppetdb_client)
  executor.finish_plan(result)

  result
end

#run_script(script, targets, arguments: [], env_vars: nil) ⇒ Bolt::ResultSet

Run a script on a list of targets.

Parameters:

  • script (String)

    The path to the script to run.

  • targets (Array[String])

    The targets to run on.

  • arguments (Array[String], NilClass) (defaults to: [])

    Arguments to pass to the script.

  • env_vars (Hash) (defaults to: nil)

    Environment variables to set on the target.

Returns:



445
446
447
448
449
450
451
452
453
# File 'lib/bolt/application.rb', line 445

def run_script(script, targets, arguments: [], env_vars: nil)
  script = find_file(script)

  Bolt::Util.validate_file('script', script)

  with_benchmark do
    executor.run_script(inventory.get_targets(targets), script, arguments, env_vars: env_vars)
  end
end

#run_task(task, targets, params: {}) ⇒ Bolt::ResultSet

Run a task on a list of targets.

Parameters:

  • task (String)

    The name of the task.

  • options (Hash)

    Additional options.

Returns:



506
507
508
509
510
511
512
# File 'lib/bolt/application.rb', line 506

def run_task(task, targets, params: {})
  targets = inventory.get_targets(targets)

  with_benchmark do
    pal.run_task(task, targets, params, executor, inventory)
  end
end

#show_guide(topic) ⇒ Boolean

Show a guide.

Parameters:

  • topic (String)

    The topic to show.

  • guides (Hash)

    A map of topics to paths to guides.

  • outputter (Bolt::Outputter)

    An outputter instance.

Returns:

  • (Boolean)


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
# File 'lib/bolt/application.rb', line 166

def show_guide(topic)
  if (path = load_guides[topic])
    analytics.event('Guide', 'known_topic', label: topic)

    begin
      guide = Bolt::Util.read_yaml_hash(path, 'guide')
    rescue SystemCallError => e
      raise Bolt::FileError("#{e.message}: unable to load guide page", filepath)
    end

    # Make sure both topic and guide keys are defined
    unless (%w[topic guide] - guide.keys).empty?
      msg = "Guide file #{path} must have a 'topic' key and 'guide' key, but has #{guide.keys} keys."
      raise Bolt::Error.new(msg, 'bolt/invalid-guide')
    end

    Bolt::Util.symbolize_top_level_keys(guide)
  else
    analytics.event('Guide', 'unknown_topic', label: topic)
    raise Bolt::Error.new(
      "Unknown topic '#{topic}'. For a list of available topics, run 'bolt guide'.",
      'bolt/unknown-topic'
    )
  end
end

#show_inventory(targets = nil) ⇒ Hash

Show inventory information.

Parameters:

  • targets (Array[String]) (defaults to: nil)

    The targets to show.

Returns:

  • (Hash)


197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/bolt/application.rb', line 197

def show_inventory(targets = nil)
  targets = group_targets_by_source(targets || ['all'])

  {
    adhoc: {
      count:   targets[:adhoc].count,
      targets: targets[:adhoc].map(&:detail)
    },
    inventory: {
      count:   targets[:inventory].count,
      targets: targets[:inventory].map(&:detail),
      file:    (inventory.source || config.default_inventoryfile).to_s,
      default: config.default_inventoryfile.to_s
    },
    targets: targets.values.flatten.map(&:detail),
    count: targets.values.flatten.count
  }
end

#show_module(name) ⇒ Hash

Show module information.

Parameters:

  • name (String)

    The name of the module.

Returns:

  • (Hash)

    The module information.



313
314
315
# File 'lib/bolt/application.rb', line 313

def show_module(name)
  pal.show_module(name)
end

#show_plan(plan) ⇒ Hash

Show plan information.

Parameters:

  • plan (String)

    The name of the plan to show.

Returns:

  • (Hash)


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

def show_plan(plan)
  pal.get_plan_info(plan)
end

#show_task(task) ⇒ Hash

Show task information.

Parameters:

  • task (String)

    The name of the task to show.

Returns:

  • (Hash)


519
520
521
# File 'lib/bolt/application.rb', line 519

def show_task(task)
  { task: pal.get_task(task) }
end

#shutdownObject

Shuts down the application.



32
33
34
# File 'lib/bolt/application.rb', line 32

def shutdown
  executor.shutdown
end

#upload_file(source, destination, targets) ⇒ Bolt::ResultSet

Upload a file from the controller to a list of targets.

Parameters:

  • source (String)

    The path to the file on the controller.

  • destination (String)

    The destination path on the targets.

  • targets (Array[String])

    The targets to run on.

Returns:



123
124
125
126
127
128
129
130
131
132
# File 'lib/bolt/application.rb', line 123

def upload_file(source, destination, targets)
  source  = find_file(source)
  targets = inventory.get_targets(targets)

  Bolt::Util.validate_file('source file', source, true)

  with_benchmark do
    executor.upload_file(targets, source, destination)
  end
end