Module: Smdev::EcsExec

Defined in:
lib/smdev/ecs_exec.rb

Class Method Summary collapse

Class Method Details

.cluster_name(options) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/smdev/ecs_exec.rb', line 26

def self.cluster_name(options)
  cluster = options[:cluster]
  command = "aws ecs list-clusters | grep #{cluster}"
  stdout, stderr, status = Open3.capture3(command)

  if status.success?
    match = stdout.match(/cluster\/([^"]+)/)
    cluster_name = match[1] if match

    return cluster_name
  else
    if stderr != ""
      puts "Error executing command: #{stderr}"
    else
      puts "Could not find cluster whose name contains \"#{cluster}\""
    end
  end
end

.service_name(options, cluster_name) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/smdev/ecs_exec.rb', line 45

def self.service_name(options, cluster_name)
  service = options[:service]
  command = "aws ecs list-services --cluster #{cluster_name} | grep #{service}\\\""
  stdout, stderr, status = Open3.capture3(command)

  unless status.success?
    command = "aws ecs list-services --cluster #{cluster_name} | grep #{service}"
    stdout, stderr, status = Open3.capture3(command)
  end

  if status.success?
    match = stdout.match(/#{cluster_name}\/([^"]+)/)
    service_name = match[1] if match

    return service_name
  else
    if stderr != ""
      puts "Error executing command: #{stderr}"
    else
      puts "Could not find service whose name contains \"#{service}\""
    end
  end
end

.ssh(options) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/smdev/ecs_exec.rb', line 5

def self.ssh(options)
  cluster_name = self.cluster_name(options)
  return if cluster_name == nil

  service_name = self.service_name(options, cluster_name)
  return if service_name == nil

  task_arn = self.task_arn(cluster_name, service_name)
  command = options[:command]

  execute_command_cmd = %W[
      aws ecs execute-command
      --cluster #{cluster_name}
      --task #{task_arn}
      --interactive
      --command \"#{command}\"
    ].join(' ')

  exec(execute_command_cmd)
end

.task_arn(cluster_name, service_name) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/smdev/ecs_exec.rb', line 69

def self.task_arn(cluster_name, service_name)
  list_tasks_cmd = "aws ecs list-tasks --cluster #{cluster_name} --service-name #{service_name}"
  stdout, stderr, status = Open3.capture3(list_tasks_cmd)

  if status.success?
    begin
      tasks = JSON.parse(stdout)
      task_arn = tasks['taskArns'][0]

      if task_arn.nil? || task_arn.empty?
        puts 'No task ARN found.'
        exit 1
      end
      return task_arn
    rescue JSON::ParserError
      puts 'Error parsing JSON'
      exit 1
    end
  else
    puts "Error executing command: #{stderr}"
    exit 1
  end
end