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

#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



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

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
  out.binmode
  err.binmode
  stdout = Thread.new { result.stdout << out.read }
  stderr = Thread.new { result.stderr << err.read }

  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



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

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



122
123
124
125
126
127
128
129
# File 'lib/bolt/shell/powershell.rb', line 122

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



113
114
115
116
117
118
119
120
# File 'lib/bolt/shell/powershell.rb', line 113

def mkdirs(dirs)
  mkdir_command = "mkdir -Force #{dirs.uniq.sort.join(',')}"
  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



78
79
80
# File 'lib/bolt/shell/powershell.rb', line 78

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

#rmdir(dir) ⇒ Object



131
132
133
# File 'lib/bolt/shell/powershell.rb', line 131

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

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



168
169
170
171
172
173
174
175
# File 'lib/bolt/shell/powershell.rb', line 168

def run_command(command, _options = {})
  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



152
153
154
155
156
157
158
159
160
161
# File 'lib/bolt/shell/powershell.rb', line 152

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



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/bolt/shell/powershell.rb', line 177

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



198
199
200
201
202
203
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
244
245
246
247
248
249
250
251
252
253
# File 'lib/bolt/shell/powershell.rb', line 198

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)
                        envify_params(arguments).map do |(arg, val)|
                          set_env(arg, val)
                        end
                      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

#set_env(arg, val) ⇒ Object



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

def set_env(arg, val)
  "[Environment]::SetEnvironmentVariable('#{arg}', @'\n#{val}\n'@)"
end

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



163
164
165
166
# File 'lib/bolt/shell/powershell.rb', line 163

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



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

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



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

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