Class: EC2Ctl::CLI

Inherits:
Object
  • Object
show all
Includes:
Commander::Methods
Defined in:
lib/ec2ctl/cli.rb

Instance Method Summary collapse

Instance Method Details

#runObject



10
11
12
13
14
15
16
17
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ec2ctl/cli.rb', line 10

def run
  program :name,        "EC2Ctl"
  program :version,     EC2Ctl::VERSION
  program :description, "A minimum tool for EC2 instances."

  global_option "-p", "--profile PROFILE", "Load AWS credentials from shared credentials file by specified name."
  global_option "-r", "--region REGION",   "Specify AWS region."

  default_command :list

  command :list do |c|
    c.syntax      = "list [options]"
    c.description = "List EC2 instances"

    c.option "-a", "--attributes STRING", String, "Attribute of EC2 instances separated by commas."
    c.option "-s", "--search STRING",     String, "Search instance with given KEY=VALUE attributes."
    c.option "-o", "--order STRING",      String, "Order list by specified attribute."
    c.option "-f", "--format STRING",     String, "Output format (table/json/yaml)."

    c.action do |args, options|
      options.default(
        attributes: "instance_id,tag:Name,instance_type,private_ip_address,public_ip_address,state.name",
        format:     "table",
        order:      "tag:Name",
      )

      set_client(options)

      search         = options.search ? options.search.split(",").map {|s| s.split("=")}.to_h : {}
      attributes     = (options.attributes.split(",") + search.keys).uniq
      instance_infos = client.instance_infos(attributes, search).sort_by {|i| i[options.order]}

      if instance_infos.empty?
        say "Instance not found."
      else
        case options.format
        when /table/i
          say Terminal::Table.new(
            headings: attributes,
            rows:     instance_infos.map {|i| attributes.map {|a| i[a]}}
          )
        when /json/i
          say JSON.pretty_generate(instance_infos)
        when /yaml/i
          say instance_infos.to_yaml
        end
      end
    end
  end

  alias_command :ls, :list

  run!
end