Class: Bolt::Shell::Powershell

Inherits:
Bolt::Shell show all
Defined in:
lib/bolt/shell/powershell.rb,
lib/bolt/shell/powershell/snippets.rb

Defined Under Namespace

Modules: Snippets

Constant Summary collapse

DEFAULT_EXTENSIONS =
Set.new(%w[.ps1 .rb .pp])
PS_ARGS =
%w[-NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass].freeze

Instance Attribute Summary

Attributes inherited from Bolt::Shell

#conn, #logger, #target

Instance Method Summary collapse

Methods inherited from Bolt::Shell

#envify_params, #select_implementation, #select_interpreter, #unwrap_sensitive_args

Constructor Details

#initialize(target, conn) ⇒ Powershell

Returns a new instance of Powershell.



11
12
13
14
15
16
17
18
# File 'lib/bolt/shell/powershell.rb', line 11

def initialize(target, conn)
  super

  extensions = [target.options['extensions'] || []].flatten.map { |ext| ext[0] == '.' ? ext : '.' + ext }
  extensions += target.options['interpreters'].keys if target.options['interpreters']
  @extensions = DEFAULT_EXTENSIONS + extensions
  validate_ps_version
end

Instance Method Details

#default_input_method(executable) ⇒ Object



38
39
40
# File 'lib/bolt/shell/powershell.rb', line 38

def default_input_method(executable)
  powershell_file?(executable) ? 'powershell' : 'both'
end

#download(source, destination, _options = {}) ⇒ Object



186
187
188
189
190
# File 'lib/bolt/shell/powershell.rb', line 186

def download(source, destination, _options = {})
  download = File.join(destination, Bolt::Util.windows_basename(source))
  conn.download_file(source, destination, download)
  Bolt::Result.for_download(target, source, destination, download)
end

#env_declarations(env_vars) ⇒ Object



89
90
91
92
93
# File 'lib/bolt/shell/powershell.rb', line 89

def env_declarations(env_vars)
  env_vars.map do |var, val|
    "[Environment]::SetEnvironmentVariable('#{var}', @'\n#{val}\n'@)"
  end
end

#escape_arguments(arguments) ⇒ Object



79
80
81
82
83
84
85
86
87
# File 'lib/bolt/shell/powershell.rb', line 79

def escape_arguments(arguments)
  arguments.map do |arg|
    if arg =~ / /
      "\"#{arg}\""
    else
      arg
    end
  end
end

#execute(command, wrap_command = false) ⇒ Object



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
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/bolt/shell/powershell.rb', line 312

def execute(command, wrap_command = false)
  if (conn.max_command_length && command.length > conn.max_command_length) ||
     wrap_command
    return with_tmpdir do |dir|
      command += "\r\nif (!$?) { if($LASTEXITCODE) { exit $LASTEXITCODE } else { exit 1 } }"
      script_file = File.join(dir, "#{SecureRandom.uuid}_wrapper.ps1")
      conn.upload_file(StringIO.new(command), script_file)
      args = escape_arguments([script_file])
      script_invocation = ['powershell.exe', *PS_ARGS, '-File', *args].join(' ')
      execute(script_invocation)
    end
  end
  inp, out, err, t = conn.execute(command)

  result = Bolt::Node::Output.new
  inp.close
  stdout = Thread.new do
    # Set to binmode to preserve \r\n line endings, but save and restore
    # the proper encoding so the string isn't later misinterpreted
    encoding = out.external_encoding
    out.binmode
    to_print = out.read.force_encoding(encoding)
    if !to_print.chomp.empty? && @stream_logger
      formatted = to_print.lines.map do |msg|
        "[#{@target.safe_name}] out: #{msg.chomp}"
      end.join("\n")
      @stream_logger.warn(formatted)
    end
    result.stdout        << to_print
    result.merged_output << to_print
  end
  stderr = Thread.new do
    encoding = err.external_encoding
    err.binmode
    to_print = err.read.force_encoding(encoding)
    if !to_print.chomp.empty? && @stream_logger
      formatted = to_print.lines.map do |msg|
        "[#{@target.safe_name}] err: #{msg.chomp}"
      end.join("\n")
      @stream_logger.warn(formatted)
    end
    result.stderr        << to_print
    result.merged_output << to_print
  end

  stdout.join
  stderr.join
  result.exit_code = t.value.respond_to?(:exitstatus) ? t.value.exitstatus : t.value

  result
end

#execute_process(path, arguments, stdin = nil) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/bolt/shell/powershell.rb', line 107

def execute_process(path, arguments, stdin = nil)
  quoted_args = arguments.map { |arg| quote_string(arg) }.join(' ')

  quoted_path = if path =~ /^'.*'$/ || path =~ /^".*"$/
                  path
                else
                  quote_string(path)
                end
  exec_cmd =
    if stdin.nil?
      "& #{quoted_path} #{quoted_args}"
    else
      <<~STR
      $command_stdin = @'
      #{stdin}
      '@

      $command_stdin | & #{quoted_path} #{quoted_args}
      STR
    end
  Snippets.execute_process(exec_cmd)
end

#make_tmpdirObject



140
141
142
143
144
145
146
147
# File 'lib/bolt/shell/powershell.rb', line 140

def make_tmpdir
  find_parent = target.options['tmpdir'] ? "\"#{target.options['tmpdir']}\"" : '[System.IO.Path]::GetTempPath()'
  result = execute(Snippets.make_tmpdir(find_parent))
  if result.exit_code != 0
    raise Bolt::Node::FileError.new("Could not make tmpdir: #{result.stderr.string}", 'TMPDIR_ERROR')
  end
  result.stdout.string.chomp
end

#mkdirs(dirs) ⇒ Object



130
131
132
133
134
135
136
137
138
# File 'lib/bolt/shell/powershell.rb', line 130

def mkdirs(dirs)
  paths = dirs.uniq.sort.join('","')
  mkdir_command = "mkdir -Force -Path (\"#{paths}\")"
  result = execute(mkdir_command)
  if result.exit_code != 0
    message = "Could not create directories: #{result.stderr.string}"
    raise Bolt::Node::FileError.new(message, 'MKDIR_ERROR')
  end
end

#powershell_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/bolt/shell/powershell.rb', line 42

def powershell_file?(path)
  File.extname(path).downcase == '.ps1'
end

#process_from_extension(path) ⇒ Object



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
# File 'lib/bolt/shell/powershell.rb', line 53

def process_from_extension(path)
  case Pathname(path).extname.downcase
  when '.rb'
    [
      'ruby.exe',
      %W[-S "#{path}"]
    ]
  when '.ps1'
    [
      'powershell.exe',
      [*PS_ARGS, '-File', path]
    ]
  when '.pp'
    [
      'puppet.bat',
      %W[apply "#{path}"]
    ]
  else
    # Run the script via cmd, letting Windows extension handling determine how
    [
      'cmd.exe',
      %W[/c "#{path}"]
    ]
  end
end

#provided_featuresObject



34
35
36
# File 'lib/bolt/shell/powershell.rb', line 34

def provided_features
  ['powershell']
end

#quote_string(string) ⇒ Object



95
96
97
# File 'lib/bolt/shell/powershell.rb', line 95

def quote_string(string)
  "'" + string.gsub("'", "''") + "'"
end

#rmdir(dir) ⇒ Object



149
150
151
# File 'lib/bolt/shell/powershell.rb', line 149

def rmdir(dir)
  execute(Snippets.rmdir(dir))
end

#run_command(command, options = {}, position = []) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
# File 'lib/bolt/shell/powershell.rb', line 192

def run_command(command, options = {}, position = [])
  command = [*env_declarations(options[:env_vars]), command].join("\r\n") if options[:env_vars]

  wrap_command = conn.is_a?(Bolt::Transport::Local::Connection)
  output = execute(command, wrap_command)
  Bolt::Result.for_command(target,
                           output.to_h,
                           'command',
                           command,
                           position)
end

#run_ps_task(task_path, arguments, input_method) ⇒ Object



170
171
172
173
174
175
176
177
178
179
# File 'lib/bolt/shell/powershell.rb', line 170

def run_ps_task(task_path, arguments, input_method)
  # NOTE: cannot redirect STDIN to a .ps1 script inside of PowerShell
  # must create new powershell.exe process like other interpreters
  # fortunately, using PS with stdin input_method should never happen
  if input_method == 'powershell'
    Snippets.ps_task(task_path, arguments)
  else
    Snippets.try_catch(task_path)
  end
end

#run_script(script, arguments, options = {}, position = []) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/bolt/shell/powershell.rb', line 204

def run_script(script, arguments, options = {}, position = [])
  # unpack any Sensitive data
  arguments = unwrap_sensitive_args(arguments)
  with_tmpdir do |dir|
    script_path = write_executable(dir, script)
    command = if powershell_file?(script_path) && options[:pwsh_params]
                # Scripts run with pwsh_params can be run like tasks
                Snippets.ps_task(script_path, options[:pwsh_params])
              elsif powershell_file?(script_path)
                Snippets.run_script(arguments, script_path)
              else
                interpreter = select_interpreter(script_path, target.options['interpreters'])
                if options[:script_interpreter] && interpreter
                  # interpreter can be a String or Array here. Cast it to an array.
                  interpreter_array = Array(interpreter)
                  # Make path the first part of the array - this should be the binary
                  path = interpreter_array.shift
                  # Anything else in interpreters should get prepended to
                  # the command. If interpreters was a string this will
                  # just be [script_path]
                  args = escape_arguments(interpreter_array + Array(script_path))
                  logger.trace("Running '#{script_path}' using '#{interpreter}' interpreter")
                else
                  path, args = *process_from_extension(script_path)
                end
                args += escape_arguments(arguments)
                execute_process(path, args)
              end
    env_assignments = options[:env_vars] ? env_declarations(options[:env_vars]) : []
    shell_init = options[:pwsh_params] ? Snippets.shell_init : ''

    output = execute([shell_init, *env_assignments, command].join("\r\n"))

    Bolt::Result.for_command(target,
                             output.to_h,
                             'script',
                             script,
                             position)
  end
end

#run_task(task, arguments, _options = {}, position = []) ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/bolt/shell/powershell.rb', line 245

def run_task(task, arguments, _options = {}, position = [])
  implementation = select_implementation(target, task)
  executable = implementation['path']
  input_method = implementation['input_method']
  extra_files = implementation['files']
  input_method ||= powershell_file?(executable) ? 'powershell' : 'both'

  # unpack any Sensitive data
  arguments = unwrap_sensitive_args(arguments)
  with_tmpdir do |dir|
    if extra_files.empty?
      task_dir = dir
    else
      # TODO: optimize upload of directories
      arguments['_installdir'] = dir
      task_dir = File.join(dir, task.tasks_dir)
      mkdirs([task_dir] + extra_files.map { |file| File.join(dir, File.dirname(file['name'])) })
      extra_files.each do |file|
        conn.upload_file(file['path'], File.join(dir, file['name']))
      end
    end

    task_path = write_executable(task_dir, executable)

    if Bolt::Task::STDIN_METHODS.include?(input_method)
      stdin = JSON.dump(arguments)
    end

    command = if powershell_file?(task_path) && stdin.nil?
                run_ps_task(task_path, arguments, input_method)
              else
                if (interpreter = select_interpreter(task_path, target.options['interpreters']))
                  # interpreter can be a String or Array here. Cast it to an array.
                  interpreter_array = Array(interpreter)
                  # Make path the first part of the array - this should be the binary
                  path = interpreter_array.shift
                  # Anything else in interpreters should get prepended to
                  # the command. If interpreters was a string this will
                  # just be [task_path]
                  args = interpreter_array + [task_path]
                else
                  path, args = *process_from_extension(task_path)
                end
                execute_process(path, args, stdin)
              end

    env_assignments = if Bolt::Task::ENVIRONMENT_METHODS.include?(input_method)
                        env_declarations(envify_params(arguments))
                      else
                        []
                      end

    output = execute([
      Snippets.shell_init,
      Snippets.append_ps_module_path(dir),
      *env_assignments,
      command
    ].join("\n"))

    Bolt::Result.for_task(target, output.stdout.string,
                          output.stderr.string,
                          output.exit_code,
                          task.name,
                          position)
  end
end

#upload(source, destination, _options = {}) ⇒ Object



181
182
183
184
# File 'lib/bolt/shell/powershell.rb', line 181

def upload(source, destination, _options = {})
  conn.upload_file(source, destination)
  Bolt::Result.for_upload(target, source, destination)
end

#validate_extensions(ext) ⇒ Object



46
47
48
49
50
51
# File 'lib/bolt/shell/powershell.rb', line 46

def validate_extensions(ext)
  unless @extensions.include?(ext)
    raise Bolt::Node::FileError.new("File extension #{ext} is not enabled, "\
                                    "to run it please add to 'winrm: extensions'", 'FILETYPE_ERROR')
  end
end

#validate_ps_versionObject



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/bolt/shell/powershell.rb', line 20

def validate_ps_version
  version = execute("$PSVersionTable.PSVersion.Major").stdout.string.chomp
  if !version.empty? && version.to_i < 3
    # This lets us know how many targets have Powershell 2, and lets the
    # user know how many targets they have with PS2
    msg = "Detected PowerShell 2 on one or more targets.\nPowerShell 2 "\
      "is unsupported. See bolt-debug.log or run with '--log-level debug' to see the full "\
      "list of targets with PowerShell 2."

    Bolt::Logger.deprecate_once("powershell_2", msg)
    @logger.debug("Detected PowerShell 2 on #{target}.")
  end
end

#with_tmpdirObject



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/bolt/shell/powershell.rb', line 153

def with_tmpdir
  unless @tmpdir
    # Only cleanup the directory afterward if we made it to begin with
    owner = true
    @tmpdir = make_tmpdir
  end
  yield @tmpdir
ensure
  if owner && @tmpdir
    if target.options['cleanup']
      rmdir(@tmpdir)
    else
      Bolt::Logger.warn("Skipping cleanup of tmpdir '#{@tmpdir}'", "skip_cleanup")
    end
  end
end

#write_executable(dir, file, filename = nil) ⇒ Object



99
100
101
102
103
104
105
# File 'lib/bolt/shell/powershell.rb', line 99

def write_executable(dir, file, filename = nil)
  filename ||= File.basename(file)
  validate_extensions(File.extname(filename))
  destination = "#{dir}\\#{filename}"
  conn.upload_file(file, destination)
  destination
end