Class: Chef::Knife::BastionStart

Inherits:
BastionBase show all
Defined in:
lib/chef/knife/bastion_start.rb

Instance Method Summary collapse

Methods inherited from BastionBase

#print_tunnel_info, #tunnel_pid

Instance Method Details

#initialize_paramsObject



19
20
21
22
23
24
25
# File 'lib/chef/knife/bastion_start.rb', line 19

def initialize_params
  super

  @timeout = config[:timeout]
  @timeout = 600  if @timeout < 1    # timeout should be greater than 0
  @timeout = 3600 if @timeout > 3600 # timeout should be less than 1 hour
end

#kill_proxy_if_runningObject



41
42
43
44
45
46
47
# File 'lib/chef/knife/bastion_start.rb', line 41

def kill_proxy_if_running
  proxy_pid = tunnel_pid(@local_port, false)
  if proxy_pid
    ui.warn "Proxy on #{@local_port} is up and running. Restarting it"
    shell_out!("kill -9 '#{proxy_pid}'")
  end
end

#runObject



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/chef/knife/bastion_start.rb', line 27

def run
  initialize_params

  # Check if proxy is already running and restart it
  kill_proxy_if_running

  print_tunnel_info("Creating a tunnel to Chef server:", timeout: @timeout)

  ui.info "Establishing connection to #{ui.color @bastion_host, [:bold, :white]}"
  ui.warn "Please make sure to use your #{ui.color @bastion_network, [:bold, :magenta]} token" if @bastion_network

  start_proxy
end

#ssh_proxy_command(timeout) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/chef/knife/bastion_start.rb', line 61

def ssh_proxy_command(timeout)
  cmd = [
    "/usr/bin/ssh",
    # go to background just before command execution
    "-f",
    # prevent reading from stdin
    "-n",
    # application-level port forwarding (SOCKS proxy)
    "-D", "127.0.0.1:#{@local_port}",
    # wait for all remote port forwards to be successfully established
    "-o", "ExitOnForwardFailure=yes",
    # Disable sharing of multiple connections
    "-o", "ControlPath=none",
    # SSH host to connect to
    "#{@bastion_user}@#{@bastion_host}",
    # Enforce tunnel timeout
    "sleep #{timeout}"
  ]
  Shellwords.join(cmd)
end

#start_proxyObject



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/chef/knife/bastion_start.rb', line 49

def start_proxy
  # Not using shell_out! here because it disables tty via Process.setsid,
  # so it will not be possible to enter password/token for bastion host.
  system ssh_proxy_command(@timeout)

  if $?.exitstatus == 0
    ui.info ui.color("OK:  ", :green) + "Successfully started proxy on port #{@local_port}"
  else
    ui.fatal "Failed to start proxy"
  end
end