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
# 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
end

Instance Method Details

#default_input_method(executable) ⇒ Object



23
24
25
# File 'lib/bolt/shell/powershell.rb', line 23

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

#env_declarations(env_vars) ⇒ Object



74
75
76
77
78
# File 'lib/bolt/shell/powershell.rb', line 74

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

#escape_arguments(arguments) ⇒ Object



64
65
66
67
68
69
70
71
72
# File 'lib/bolt/shell/powershell.rb', line 64

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

#execute(command) ⇒ Object



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

def execute(command)
  if conn.max_command_length && command.length > conn.max_command_length
    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.copy_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
    result.stdout << out.read.force_encoding(encoding)
  end
  stderr = Thread.new do
    encoding = err.external_encoding
    err.binmode
    result.stderr << err.read.force_encoding(encoding)
  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



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/bolt/shell/powershell.rb', line 92

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



125
126
127
128
129
130
131
132
# File 'lib/bolt/shell/powershell.rb', line 125

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



115
116
117
118
119
120
121
122
123
# File 'lib/bolt/shell/powershell.rb', line 115

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)


27
28
29
# File 'lib/bolt/shell/powershell.rb', line 27

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

#process_from_extension(path) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/bolt/shell/powershell.rb', line 38

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



19
20
21
# File 'lib/bolt/shell/powershell.rb', line 19

def provided_features
  ['powershell']
end

#quote_string(string) ⇒ Object



80
81
82
# File 'lib/bolt/shell/powershell.rb', line 80

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

#rmdir(dir) ⇒ Object



134
135
136
# File 'lib/bolt/shell/powershell.rb', line 134

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

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



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

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

  output = execute(command)
  Bolt::Result.for_command(target,
                           output.stdout.string,
                           output.stderr.string,
                           output.exit_code,
                           'command', command)
end

#run_ps_task(task_path, arguments, input_method) ⇒ Object



155
156
157
158
159
160
161
162
163
164
# File 'lib/bolt/shell/powershell.rb', line 155

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 = {}) ⇒ Object



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/bolt/shell/powershell.rb', line 182

def run_script(script, arguments, options = {})
  # 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)
                Snippets.run_script(arguments, script_path)
              else
                path, args = *process_from_extension(script_path)
                args += escape_arguments(arguments)
                execute_process(path, args)
              end
    command = [*env_declarations(options[:env_vars]), command].join("\r\n") if options[:env_vars]

    output = execute(command)
    Bolt::Result.for_command(target,
                             output.stdout.string,
                             output.stderr.string,
                             output.exit_code,
                             'script', script)
  end
end

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



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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/bolt/shell/powershell.rb', line 205

def run_task(task, arguments, _options = {})
  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.copy_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']))
                  path = interpreter
                  args = [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, *env_assignments, command].join("\n"))

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

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



166
167
168
169
# File 'lib/bolt/shell/powershell.rb', line 166

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

#validate_extensions(ext) ⇒ Object



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

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

#with_tmpdirObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/bolt/shell/powershell.rb', line 138

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
      @logger.warn("Skipping cleanup of tmpdir '#{@tmpdir}'")
    end
  end
end

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



84
85
86
87
88
89
90
# File 'lib/bolt/shell/powershell.rb', line 84

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