Class: Bolt::Transport::WinRM

Inherits:
Base
  • Object
show all
Defined in:
lib/bolt/transport/winrm.rb,
lib/bolt/transport/winrm/connection.rb

Defined Under Namespace

Classes: Connection

Constant Summary collapse

PS_ARGS =
%w[
  -NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass
].freeze
PROVIDED_FEATURES =
['powershell'].freeze

Constants inherited from Base

Base::ENVIRONMENT_METHODS, Base::STDIN_METHODS

Instance Attribute Summary

Attributes inherited from Base

#logger

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#assert_batch_size_one, #batch_command, #batch_script, #batch_task, #batch_upload, #batches, #envify_params, #filter_options, #from_api?, #unwrap_sensitive_args, #with_events

Constructor Details

#initializeWinRM

Returns a new instance of WinRM.



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

def initialize
  super
  require 'winrm'
  require 'winrm-fs'

  @transport_logger = Logging.logger[::WinRM]
  @transport_logger.level = :warn
end

Class Method Details

.optionsObject



12
13
14
# File 'lib/bolt/transport/winrm.rb', line 12

def self.options
  %w[port user password connect-timeout ssl ssl-verify tmpdir cacert extensions]
end

.validate(options) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/bolt/transport/winrm.rb', line 18

def self.validate(options)
  ssl_flag = options['ssl']
  unless !!ssl_flag == ssl_flag
    raise Bolt::ValidationError, 'ssl option must be a Boolean true or false'
  end

  ssl_verify_flag = options['ssl-verify']
  unless !!ssl_verify_flag == ssl_verify_flag
    raise Bolt::ValidationError, 'ssl-verify option must be a Boolean true or false'
  end

  timeout_value = options['connect-timeout']
  unless timeout_value.is_a?(Integer) || timeout_value.nil?
    error_msg = "connect-timeout value must be an Integer, received #{timeout_value}:#{timeout_value.class}"
    raise Bolt::ValidationError, error_msg
  end
end

Instance Method Details

#escape_arguments(arguments) ⇒ Object



205
206
207
208
209
210
211
212
213
# File 'lib/bolt/transport/winrm.rb', line 205

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

#powershell_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


175
176
177
# File 'lib/bolt/transport/winrm.rb', line 175

def powershell_file?(path)
  Pathname(path).extname.casecmp('.ps1').zero?
end

#process_from_extension(path) ⇒ Object



179
180
181
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/transport/winrm.rb', line 179

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

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



64
65
66
67
68
69
# File 'lib/bolt/transport/winrm.rb', line 64

def run_command(target, command, _options = {})
  with_connection(target) do |conn|
    output = conn.execute(command)
    Bolt::Result.for_command(target, output.stdout.string, output.stderr.string, output.exit_code)
  end
end

#run_script(target, script, arguments, _options = {}) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/bolt/transport/winrm.rb', line 71

def run_script(target, script, arguments, _options = {})
  # unpack any Sensitive data
  arguments = unwrap_sensitive_args(arguments)

  with_connection(target) do |conn|
    conn.with_remote_tempdir do |dir|
      remote_path = conn.write_remote_executable(dir, script)
      if powershell_file?(remote_path)
        mapped_args = arguments.map do |a|
          "$invokeArgs.ArgumentList += @'\n#{a}\n'@"
        end.join("\n")
        output = conn.execute("$invokeArgs = @{\n  ScriptBlock = (Get-Command \"\#{remote_path}\").ScriptBlock\n  ArgumentList = @()\n}\n\#{mapped_args}\n\ntry\n{\n  Invoke-Command @invokeArgs\n}\ncatch\n{\n  Write-Error $_.Exception\n  exit 1\n}\n    PS\n      else\n        path, args = *process_from_extension(remote_path)\n        args += escape_arguments(arguments)\n        output = conn.execute_process(path, args)\n      end\n      Bolt::Result.for_command(target, output.stdout.string, output.stderr.string, output.exit_code)\n    end\n  end\nend\n")

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



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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/bolt/transport/winrm.rb', line 109

def run_task(target, task, arguments, _options = {})
  if from_api?(task)
    executable = task.file['filename']
    file_content = StringIO.new(Base64.decode64(task.file['file_content']))
    input_method = task.['input_method']
  else
    implementation = task.select_implementation(target, PROVIDED_FEATURES)
    executable = implementation['path']
    input_method = implementation['input_method']
  end
  input_method ||= powershell_file?(executable) ? 'powershell' : 'both'

  # unpack any Sensitive data
  arguments = unwrap_sensitive_args(arguments)
  with_connection(target) do |conn|
    if STDIN_METHODS.include?(input_method)
      stdin = JSON.dump(arguments)
    end

    if ENVIRONMENT_METHODS.include?(input_method)
      envify_params(arguments).each do |(arg, val)|
        cmd = "[Environment]::SetEnvironmentVariable('#{arg}', @'\n#{val}\n'@)"
        result = conn.execute(cmd)
        if result.exit_code != 0
          raise Bolt::Node::EnvironmentVarError.new(arg, val)
        end
      end
    end

    conn.with_remote_tempdir do |dir|
      remote_task_path = if from_api?(task)
                           conn.write_executable_from_content(dir, file_content, executable)
                         else
                           conn.write_remote_executable(dir, executable)
                         end
      conn.shell_init
      output =
        if powershell_file?(remote_task_path) && stdin.nil?
          # 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'
            conn.execute("$private:tempArgs = Get-ContentAsJson (\n  $utf8.GetString([System.Convert]::FromBase64String('\#{Base64.encode64(JSON.dump(arguments))}'))\n)\n$allowedArgs = (Get-Command \"\#{remote_task_path}\").Parameters.Keys\n$private:taskArgs = @{}\n$private:tempArgs.Keys | ? { $allowedArgs -contains $_ } | % { $private:taskArgs[$_] = $private:tempArgs[$_] }\ntry { & \"\#{remote_task_path}\" @taskArgs } catch { Write-Error $_.Exception; exit 1 }\n        PS\n          else\n            conn.execute(%(try { & \"\#{remote_task_path}\" } catch { Write-Error $_.Exception; exit 1 }))\n          end\n        else\n          path, args = *process_from_extension(remote_task_path)\n          conn.execute_process(path, args, stdin)\n        end\n\n      Bolt::Result.for_task(target, output.stdout.string,\n                            output.stderr.string,\n                            output.exit_code)\n    end\n  end\nend\n")

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



57
58
59
60
61
62
# File 'lib/bolt/transport/winrm.rb', line 57

def upload(target, source, destination, _options = {})
  with_connection(target) do |conn|
    conn.write_remote_file(source, destination)
    Bolt::Result.for_upload(target, source, destination)
  end
end

#with_connection(target) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/bolt/transport/winrm.rb', line 45

def with_connection(target)
  conn = Connection.new(target, @transport_logger)
  conn.connect
  yield conn
ensure
  begin
    conn&.disconnect
  rescue StandardError => ex
    logger.info("Failed to close connection to #{target.uri} : #{ex.message}")
  end
end