Class: AwsEc2Environment::SsmPortForwardingSession

Inherits:
Object
  • Object
show all
Defined in:
lib/aws_ec2_environment/ssm_port_forwarding_session.rb

Defined Under Namespace

Classes: SessionIdNotFoundError, SessionProcessError, SessionTimedOutError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(instance_id, remote_port, local_port: nil, logger: Logger.new($stdout), timeout: 15, reason: nil) ⇒ SsmPortForwardingSession

rubocop:disable Metrics/ParameterLists



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/aws_ec2_environment/ssm_port_forwarding_session.rb', line 23

def initialize(
  instance_id, remote_port,
  local_port: nil, logger: Logger.new($stdout),
  timeout: 15, reason: nil
)
  # rubocop:enable Metrics/ParameterLists
  @logger = logger
  @instance_id = instance_id
  @remote_port = remote_port
  @local_port = nil
  @timeout = timeout

  @reader, @writer, @pid = PTY.spawn(ssm_port_forward_cmd(local_port, reason))

  @cmd_output = ""
  @session_id = wait_for_session_id

  @logger.info("SSM session #{@session_id} opening, forwarding port #{remote_port} on #{instance_id}")
end

Instance Attribute Details

#instance_idString (readonly)

Returns:

  • (String)


14
15
16
# File 'lib/aws_ec2_environment/ssm_port_forwarding_session.rb', line 14

def instance_id
  @instance_id
end

#pidString (readonly)

Returns:

  • (String)


20
21
22
# File 'lib/aws_ec2_environment/ssm_port_forwarding_session.rb', line 20

def pid
  @pid
end

#remote_portNumber (readonly)

Returns:

  • (Number)


17
18
19
# File 'lib/aws_ec2_environment/ssm_port_forwarding_session.rb', line 17

def remote_port
  @remote_port
end

Instance Method Details

#closeObject



43
44
45
46
47
48
49
50
# File 'lib/aws_ec2_environment/ssm_port_forwarding_session.rb', line 43

def close
  @logger.info "Terminating SSM session #{@session_id}..."
  resp = Aws::SSM::Client.new.terminate_session({ session_id: @session_id })
  @logger.info "Terminated SSM session #{resp.session_id} successfully"

  @reader.close
  @writer.close
end

#wait_for_local_portObject



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

def wait_for_local_port
  _, local_port = expect_cmd_output(/Port (\d+) opened for sessionId #{@session_id}.\r?\n/, @timeout) || []

  if local_port.nil?
    raise(
      SessionTimedOutError,
      "SSM session #{@session_id} did not become ready within #{@timeout} seconds (maybe increase the timeout?)"
    )
  end

  local_port.to_i
end