Class: Bolt::Plugin::Module

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

Defined Under Namespace

Classes: InvalidPluginData

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mod:, context:, config:, **_opts) ⇒ Module



29
30
31
32
33
# File 'lib/bolt/plugin/module.rb', line 29

def initialize(mod:, context:, config:, **_opts)
  @module = mod
  @config = config
  @context = context
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



27
28
29
# File 'lib/bolt/plugin/module.rb', line 27

def config
  @config
end

Class Method Details

.load(name, modules, opts) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/bolt/plugin/module.rb', line 15

def self.load(name, modules, opts)
  mod = modules[name]
  if mod&.plugin?
    opts[:mod] = mod
    plugin = Bolt::Plugin::Module.new(opts)
    plugin.setup
    plugin
  else
    raise PluginError::Unknown, name
  end
end

Instance Method Details

#config?Boolean



53
54
55
# File 'lib/bolt/plugin/module.rb', line 53

def config?
  @data.include?('config') && !@data['config'].empty?
end

#find_hooks(hook_data) ⇒ Object

Raises:



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/bolt/plugin/module.rb', line 105

def find_hooks(hook_data)
  raise InvalidPluginData.new("'hooks' must be a hash", name) unless hook_data.is_a?(Hash)

  hooks = {}
  # Load hooks specified in the config
  hook_data.each do |hook_name, hook_spec|
    unless hook_spec.is_a?(Hash) && hook_spec['task'].is_a?(String)
      msg = "Unexpected hook specification #{hook_spec.to_json} in #{@name} for hook #{hook_name}"
      raise InvalidPluginData.new(msg, name)
    end

    begin
      task = @context.get_validated_task(hook_spec['task'])
    rescue Bolt::Error => e
      msg = if e.kind == 'bolt/unknown-task'
              "Plugin #{name} specified an unkown task '#{hook_spec['task']}' for a hook"
            else
              "Plugin #{name} could not load task '#{hook_spec['task']}': #{e.message}"
            end
      raise InvalidPluginData.new(msg, name)
    end

    hooks[hook_name.to_sym] = { 'task' => task }
  end

  # Check for tasks for any hooks not already defined
  (Set.new(KNOWN_HOOKS.map) - hooks.keys).each do |hook_name|
    task_name = "#{name}::#{hook_name}"
    begin
      task = @context.get_validated_task(task_name)
    rescue Bolt::Error => e
      raise e unless e.kind == 'bolt/unknown-task'
    end
    hooks[hook_name] = { 'task' => task } if task
  end

  Bolt::Util.symbolize_top_level_keys(hooks)
end

#hooksObject



49
50
51
# File 'lib/bolt/plugin/module.rb', line 49

def hooks
  (@hook_map.keys + [:validate_resolve_reference]).uniq
end

#load_dataObject



57
58
59
60
61
# File 'lib/bolt/plugin/module.rb', line 57

def load_data
  JSON.parse(File.read(@module.plugin_data_file))
rescue JSON::ParserError => e
  raise InvalidPluginData.new(e.message, name)
end

#nameObject



45
46
47
# File 'lib/bolt/plugin/module.rb', line 45

def name
  @module.name
end

#process_params(task, opts) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/bolt/plugin/module.rb', line 148

def process_params(task, opts)
  # opts are passed directly from inventory but all of the _ options are
  # handled previously. That may not always be the case so filter them
  # out now.
  _meta, params = opts.partition { |key, _val| key.start_with?('_') }.map(&:to_h)

  metaparams = {}
  metaparams['_config'] = config if config?
  metaparams['_boltdir'] = @context.boltdir

  validate_params(task, params)
  [params, metaparams]
end

#process_schema(schema) ⇒ Object

Raises:



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/bolt/plugin/module.rb', line 63

def process_schema(schema)
  raise InvalidPluginData.new('config specification is not an object', name) unless schema.is_a?(Hash)
  schema.each do |key, val|
    unless key =~ /\A[a-z][a-z0-9_]*\z/
      raise InvalidPluginData.new("config specification key, '#{key}',  is not allowed", name)
    end

    unless val.is_a?(Hash) && (val['type'] || '').is_a?(String)
      raise InvalidPluginData.new("config specification #{val.to_json} is not allowed", name)
    end

    type_string = val['type'] || 'Any'
    begin
      val['pcore_type'] = Puppet::Pops::Types::TypeParser.singleton.parse(type_string)
      if val['pcore_type'].is_a? Puppet::Pops::Types::PTypeReferenceType
        raise InvalidPluginData.new("Could not find type '#{type_string}' for #{key}", name)
      end
    rescue Puppet::ParseError
      raise InvalidPluginData.new("Could not parse type '#{type_string}' for #{key}", name)
    end
  end

  schema
end

#puppet_library(opts, target, apply_prep) ⇒ Object



222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/bolt/plugin/module.rb', line 222

def puppet_library(opts, target, apply_prep)
  tasksig = @hook_map[:puppet_library]

  # this also validates
  params, meta_params = process_params(tasksig, opts)

  # our metaparams are meant for the task not the executor
  params = params.merge(meta_params)
  task = Bolt::Task.new(tasksig)

  proc do
    apply_prep.run_task([target], task, params).first
  end
end

#resolve_reference(opts) ⇒ Object

These are all the same but are defined explicitly for clarity



206
207
208
# File 'lib/bolt/plugin/module.rb', line 206

def resolve_reference(opts)
  run_hook(__method__, opts)
end

#run_hook(hook_name, opts, value = true) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/bolt/plugin/module.rb', line 177

def run_hook(hook_name, opts, value = true)
  hook = @hook_map[hook_name]
  # This shouldn't happen if the Plugin api is used
  raise PluginError::UnsupportedHook.new(name, hook_name) unless hook
  result = run_task(hook['task'], opts)

  if value
    unless result.include?('value')
      msg = "Plugin #{name} result did not include a value, got #{result}"
      raise Bolt::Plugin::PluginError::ExecutionError.new(msg, name, hook_name)
    end

    result['value']
  end
end

#run_task(task, opts) ⇒ Object

Raises:



162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/bolt/plugin/module.rb', line 162

def run_task(task, opts)
  params, metaparams = process_params(task, opts)
  params = params.merge(metaparams)

  # There are no executor options to pass now.
  options = { "_catch_errors" => true }

  result = @context.run_local_task(task,
                                   params,
                                   options).first

  raise Bolt::Error.new(result.error_hash['msg'], result.error_hash['kind']) unless result.ok
  result.value
end

#secret_createkeys(opts = {}) ⇒ Object



218
219
220
# File 'lib/bolt/plugin/module.rb', line 218

def secret_createkeys(opts = {})
  run_hook(__method__, opts)
end

#secret_decrypt(opts) ⇒ Object



214
215
216
# File 'lib/bolt/plugin/module.rb', line 214

def secret_decrypt(opts)
  run_hook(__method__, opts)
end

#secret_encrypt(opts) ⇒ Object



210
211
212
# File 'lib/bolt/plugin/module.rb', line 210

def secret_encrypt(opts)
  run_hook(__method__, opts)
end

#setupObject

This method interacts with the module on disk so it’s separate from initialize



36
37
38
39
40
41
42
43
# File 'lib/bolt/plugin/module.rb', line 36

def setup
  @data = load_data
  @config_schema = process_schema(@data['config'] || {})

  @hook_map = find_hooks(@data['hooks'] || {})

  validate_config(@config, @config_schema)
end

#validate_config(config, config_schema) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/bolt/plugin/module.rb', line 88

def validate_config(config, config_schema)
  config.keys.each do |key|
    msg = "Config for #{name} plugin contains unexpected key #{key}"
    raise Bolt::ValidationError, msg unless config_schema.include?(key)
  end

  config_schema.each do |key, spec|
    val = config[key]

    unless spec['pcore_type'].instance?(val)
      raise Bolt::ValidationError, "#{name} plugin expects a #{spec['type']} for key #{key}, got: #{val}"
    end
    val.nil?
  end
  nil
end

#validate_params(task, params) ⇒ Object



144
145
146
# File 'lib/bolt/plugin/module.rb', line 144

def validate_params(task, params)
  @context.validate_params(task.name, params)
end

#validate_resolve_reference(opts) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
# File 'lib/bolt/plugin/module.rb', line 193

def validate_resolve_reference(opts)
  params = opts.reject { |k, _v| k.start_with?('_') }
  sig = @hook_map[:resolve_reference]['task']
  if sig
    validate_params(sig, params)
  end

  if @hook_map.include?(:validate_resolve_reference)
    run_hook(:validate_resolve_reference, opts, false)
  end
end