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



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.



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.



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, ext_glob: true)

  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

#apply_policies(policies, targets, noop: false) ⇒ Bolt::ResultSet

Applies one or more policies to the specified targets.



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/bolt/application.rb', line 427

def apply_policies(policies, targets, noop: false)
  policies = policies.split(',')

  # Validate that the policies are available to the project.
  unavailable_policies = policies.reject do |policy|
    @config.policies&.any? do |known_policy|
      File.fnmatch?(known_policy, policy, File::FNM_EXTGLOB)
    end
  end

  if unavailable_policies.any?
    command = Bolt::Util.powershell? ? 'Get-BoltPolicy' : 'bolt policy show'

    # CODEREVIEW: Phrasing
    raise Bolt::Error.new(
      "The following policies are not available to the project: '#{unavailable_policies.join("', '")}'. "\
      "You must list policies in a project's 'policies' setting before Bolt can apply them to targets. "\
      "For a list of policies available to the project, run '#{command}'.",
      'bolt/unavailable-policy-error'
    )
  end

  # Validate that the policies are loadable Puppet classes.
  unloadable_policies = []

  @pal.in_catalog_compiler do |_|
    environment = Puppet.lookup(:current_environment)

    unloadable_policies = policies.reject do |policy|
      environment.known_resource_types.find_hostclass(policy)
    end
  end

  # CODEREVIEW: Phrasing
  if unloadable_policies.any?
    raise Bolt::Error.new(
      "The following policies cannot be loaded: '#{unloadable_policies.join("', '")}'. "\
      "Policies must be a Puppet class saved to a project's or module's manifests directory.",
      'bolt/unloadable-policy-error'
    )
  end

  # Execute a single include statement with all the policies to apply them
  # to the targets. Yay, reusable code!
  apply(nil, targets, code: "include #{policies.join(', ')}", noop: noop)
end

#convert_plan(plan) ⇒ String

Convert a YAML plan to a Puppet language 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.



599
600
601
602
# File 'lib/bolt/application.rb', line 599

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.



640
641
642
643
644
645
646
647
# File 'lib/bolt/application.rb', line 640

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.



655
656
657
658
659
660
661
662
# File 'lib/bolt/application.rb', line 655

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.



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, ext_glob: true)

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

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

Encrypt plaintext using the configured secret plugin.



670
671
672
673
674
675
676
677
# File 'lib/bolt/application.rb', line 670

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.



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.



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.



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.



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.



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.



405
406
407
408
409
410
# File 'lib/bolt/application.rb', line 405

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.



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

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

#list_policiesHash

List policies available to the project.



576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'lib/bolt/application.rb', line 576

def list_policies
  unless @config.policies
    command = Bolt::Util.powershell? ? 'New-BoltPolicy -Name <NAME>' : 'bolt policy new <NAME>'

    raise Bolt::Error.new(
      "Project configuration file #{@config.project.project_file} does not "\
      "specify any policies. You can add policies to the project by including "\
      "a 'policies' key or creating a new policy using the '#{command}' "\
      "command.",
      'bolt/no-policies-error'
    )
  end

  { policies: @config.policies.uniq, modulepath: pal.user_modulepath }
end

#list_tasks(filter: nil) ⇒ Hash

List available tasks.



707
708
709
710
711
712
# File 'lib/bolt/application.rb', line 707

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.



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, ext_glob: true),
               inventory,
               executor,
               plan_vars: vars)
  end
end

#migrate_project(outputter) ⇒ Boolean

Migrate a project to current best practices.



609
610
611
# File 'lib/bolt/application.rb', line 609

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.



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

#new_policy(name) ⇒ Hash

Add a new policy to the project.



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'lib/bolt/application.rb', line 479

def new_policy(name)
  # Validate the policy name
  unless name =~ Bolt::Module::CONTENT_NAME_REGEX
    message = "      Invalid policy name '\#{name}'. Policy names are composed of one or more name segments\n      separated by double colons '::'.\n\n      Each name segment must begin with a lowercase letter, and can only include lowercase\n      letters, digits, and underscores.\n\n      Examples of valid policy names:\n          - \#{@config.project.name}\n          - \#{@config.project.name}::my_policy\n    MESSAGE\n\n    raise Bolt::ValidationError, message\n  end\n\n  # Validate that we're not running with the default project\n  if @config.project.name.nil?\n    command = Bolt::Util.powershell? ? 'New-BoltProject -Name <NAME>' : 'bolt project init <NAME>'\n    message = <<~MESSAGE.chomp\n      Can't create a policy for the default Bolt project because it doesn't\n      have a name. Run '\#{command}' to create a new project.\n    MESSAGE\n    raise Bolt::ValidationError, message\n  end\n\n  prefix, *name_segments, basename = name.split('::')\n\n  # Error if name is not namespaced to project\n  unless prefix == @config.project.name\n    raise Bolt::ValidationError,\n          \"Policy name '\#{name}' must begin with project name '\#{@config.project.name}'. Did \"\\\n          \"you mean '\#{@config.project.name}::\#{name}'?\"\n  end\n\n  # If the policy name is just the project name, use the special init.pp class\n  basename ||= 'init'\n\n  # Policies can be saved in subdirectories in the 'manifests/' directory\n  policy_dir = File.expand_path(File.join(name_segments), @config.project.manifests)\n  policy     = File.expand_path(\"\#{basename}.pp\", policy_dir)\n\n  # Ensure the policy does not already exist\n  if File.exist?(policy)\n    raise Bolt::Error.new(\n      \"A policy with the name '\#{name}' already exists at '\#{policy}', nothing to do.\",\n      'bolt/existing-policy-error'\n    )\n  end\n\n  # Create the policy directory structure in the current project\n  begin\n    FileUtils.mkdir_p(policy_dir)\n  rescue Errno::EEXIST => e\n    raise Bolt::Error.new(\n      \"\#{e.message}; unable to create manifests directory '\#{policy_dir}'\",\n      'bolt/existing-file-error'\n    )\n  end\n\n  # Create the new policy\n  begin\n    File.write(policy, <<~POLICY)\n      class \#{name} {\n\n      }\n    POLICY\n  rescue Errno::EACCES => e\n    raise Bolt::FileError.new(\"\#{e.message}; unable to create policy\", policy)\n  end\n\n  # Update the project configuration to include the new policy\n  project_config = Bolt::Util.read_yaml_hash(@config.project.project_file, 'project config')\n\n  # Add the 'policies' key if it does not exist and de-dupiclate entries\n  project_config['policies'] ||= []\n  project_config['policies'] <<  name\n  project_config['policies'].uniq!\n\n  begin\n    File.write(@config.project.project_file, project_config.to_yaml)\n  rescue Errno::EACCES => e\n    raise Bolt::FileError.new(\n      \"\#{e.message}; unable to update project configuration\",\n      @config.project.project_file\n    )\n  end\n\n  { name: name, path: policy }\nend\n".chomp

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

Lookup a value with Hiera using plan_hierarchy.



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.



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, ext_glob: true)

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

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

Run a plan.



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
386
387
388
389
# File 'lib/bolt/application.rb', line 353

def run_plan(plan, targets, params: {})
  plan_params = pal.get_plan_info(plan)['parameters']
  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

    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

  sensitive_params = params.keys.select { |param| plan_params.dig(param, 'sensitive') }

  plan_context = { plan_name: plan, params: params, sensitive: sensitive_params }

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

  result
rescue Bolt::Error => e
  Bolt::PlanResult.new(e, 'failure')
end

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

Run a script on a list of targets.



621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/bolt/application.rb', line 621

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, ext_glob: true),
                        script,
                        arguments,
                        env_vars: env_vars)
  end
end

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

Run a task on a list of targets.



685
686
687
688
689
690
691
# File 'lib/bolt/application.rb', line 685

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

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

#show_guide(topic) ⇒ Boolean

Show a guide.



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.



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.



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.



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

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

#show_task(task) ⇒ Hash

Show task information.



698
699
700
# File 'lib/bolt/application.rb', line 698

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.



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, ext_glob: true)

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

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