Class: SSHKit::EC2InstanceConnect::Tunnel

Inherits:
Object
  • Object
show all
Defined in:
lib/sshkit/ec2instanceconnect/tunnel.rb

Overview

Manages a tunnel using the EC2 Instance Connect Endpoint Service, for secure SSH access to EC2 instances.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(instance_id:, host: 'localhost', port: '8000') ⇒ Tunnel

Returns a new instance of Tunnel.



11
12
13
14
15
# File 'lib/sshkit/ec2instanceconnect/tunnel.rb', line 11

def initialize(instance_id:, host: 'localhost', port: '8000')
  @instance_id = instance_id
  @host = host
  @port = port
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



9
10
11
# File 'lib/sshkit/ec2instanceconnect/tunnel.rb', line 9

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



9
10
11
# File 'lib/sshkit/ec2instanceconnect/tunnel.rb', line 9

def port
  @port
end

Instance Method Details

#startObject

Start the tunnel subprocess and wait until it is listening for connections.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sshkit/ec2instanceconnect/tunnel.rb', line 18

def start
  mutex = Mutex.new
  condition = ConditionVariable.new
  ready = false
  error = nil

  @thread = Thread.new do
    PTY.spawn(command) do |stdout, _stdin, pid|
      @pid = pid

      stdout.each_line do |line|
        next unless line.start_with?('Listening for connections')

        mutex.synchronize do
          ready = true
          condition.signal
        end
      end
    rescue Errno::EIO
      # PTY closed — safe to ignore
    end
  rescue Errno::ENOENT => e
    mutex.synchronize do
      error = e
      condition.signal
    end
  end

  mutex.synchronize { condition.wait(mutex) until ready || error }

  raise error if error
end

#stopObject

Stop the tunnel process.



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/sshkit/ec2instanceconnect/tunnel.rb', line 52

def stop
  return if @pid.nil?

  begin
    Process.kill('TERM', @pid)
  rescue Errno::ESRCH
    # Process already exited — safe to ignore
  end
  @pid = nil

  @thread&.join
end

#to_sObject



65
66
67
# File 'lib/sshkit/ec2instanceconnect/tunnel.rb', line 65

def to_s
  "#{@host}:#{@port}"
end