Class: Moose::Inventory::Cli::Host

Inherits:
Thor
  • Object
show all
Includes:
Helpers
Defined in:
lib/moose_inventory/cli/host.rb,
lib/moose_inventory/cli/host_rm.rb,
lib/moose_inventory/cli/host_add.rb,
lib/moose_inventory/cli/host_get.rb,
lib/moose_inventory/cli/host_list.rb,
lib/moose_inventory/cli/host_rmvar.rb,
lib/moose_inventory/cli/host_addvar.rb,
lib/moose_inventory/cli/host_rmgroup.rb,
lib/moose_inventory/cli/host_addgroup.rb,
lib/moose_inventory/cli/host_listvars.rb

Overview

implementation of the “host listvars” method of the CLI

Constant Summary

Constants included from Helpers

Moose::Inventory::Cli::Helpers::AUTOMATIC_GROUP

Instance Method Summary collapse

Instance Method Details

#add(*argv) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/moose_inventory/cli/host_add.rb', line 22

def add(*argv)
  abort_if_missing_args(argv, 1, '1 or more')

  # Arguments
  names = normalize_names(argv)

  # split(/\W+/) splits on hyphens too, which is not what we want
  # groups = options[:groups].downcase.split(/\W+/).uniq
  groups = csv_option_names(options[:groups])

  # Sanity
  abort_if_automatic_group(groups)

  result = Moose::Inventory::Operations::AddHosts
           .new(context: Moose::Inventory::InventoryContext.new(db: db))
           .call(names: names, groups: groups)
  render_add_hosts_events(result.events)
  puts 'Succeeded'
end

#addgroup(*args) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/moose_inventory/cli/host_addgroup.rb', line 19

def addgroup(*args)
  abort_if_missing_args(args, 2, '2 or more')

  name = args[0].downcase
  groups = normalize_names(args.slice(1, args.length - 1))

  abort_if_automatic_group(groups)

  context = Moose::Inventory::InventoryContext.new(db: db)
  operation = Moose::Inventory::Operations::AddAssociations.new(context: context)

  db.transaction do
    puts "Associate host '#{name}' with groups '#{groups.join(',')}':"
    host = fetch_existing_host_for_addgroup(context, name)
    render_host_addgroup_events(
      operation.host_to_groups(host: host, host_name: name, group_names: groups).events
    )
    fmt.puts 2, '- All OK'
  end

  puts 'Succeeded'
end

#addvar(*args) ⇒ Object

rubocop:disable Metrics/LineLength



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
64
65
66
67
68
69
70
71
72
73
# File 'lib/moose_inventory/cli/host_addvar.rb', line 16

def addvar(*args) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
  # rubocop:enable Metrics/LineLength
  if args.length < 2
    abort('ERROR: Wrong number of arguments, '\
          "#{args.length} for 2 or more.")
  end

  # Convenience
  db = Moose::Inventory::DB
  fmt = Moose::Inventory::Cli::Formatter

  # Arguments
  name = args[0].downcase
  vars = args.slice(1, args.length - 1).uniq

  # Transaction
  db.transaction do # Transaction start
    puts "Add variables '#{vars.join(',')}' to host '#{name}':"

    fmt.puts 2, "- retrieve host '#{name}'..."
    host = db.models[:host].find(name: name)
    if host.nil?
      fail db.exceptions[:moose],
           "The host '#{name}' does not exist."
    end
    fmt.puts 4, '- OK'

    hostvars_ds = host.hostvars_dataset
    vars.each do |v|
      fmt.puts 2, "- add variable '#{v}'..."
      vararray = v.split('=')
      if v.start_with?('=') || v.end_with?('=') || vararray.length != 2
        fail db.exceptions[:moose],
             "Incorrect format in '{#{v}}'. Expected 'key=value'."
      end

      # Check against existing associations
      hostvar = hostvars_ds[name: vararray[0]]
      if !hostvar.nil?
        unless hostvar[:value] == vararray[1]
          fmt.puts 4, '- already exists, applying as an update...'
          update = db.models[:hostvar].find(id: hostvar[:id])
          update[:value] = vararray[1]
          update.save
        end
      else
        # hostvar doesn't exist, so create and associate
        hostvar = db.models[:hostvar].create(name: vararray[0],
                                             value: vararray[1])
        host.add_hostvar(hostvar)
      end
      fmt.puts 4, '- OK'
    end
    fmt.puts 2, '- all OK'
  end # Transaction end

  puts 'Succeeded.'
end

#get(*argv) ⇒ Object

rubocop:disable Metrics/AbcSize



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
# File 'lib/moose_inventory/cli/host_get.rb', line 18

def get(*argv) # rubocop:disable Metrics/AbcSize
  if argv.empty?
    abort('ERROR: Wrong number of arguments, '\
      "#{argv.length} for 1 or more")
  end

  # Convenience
  db = Moose::Inventory::DB
  fmt = Moose::Inventory::Cli::Formatter

  # Arguments
  names = argv.uniq.map(&:downcase)

  # Process
  results = {}
  names.each do |name|
    host = db.models[:host].find(name: name)

    next if host.nil?
    groups = host.groups_dataset.map(:name)

    hostvars = {}
    host.hostvars_dataset.each do |hv|
      hostvars[hv[:name].to_sym] = hv[:value]
    end

    results[host[:name].to_sym] = {}
    results[host[:name].to_sym][:groups] = groups unless groups.empty?
    unless hostvars.empty?
      results[host[:name].to_sym][:hostvars] = hostvars
    end
  end

  fmt.dump(results)
end

#listObject

rubocop:disable Metrics/AbcSize



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/moose_inventory/cli/host_list.rb', line 14

def list # rubocop:disable Metrics/AbcSize
  # Convenience
  db = Moose::Inventory::DB
  fmt = Moose::Inventory::Cli::Formatter

  # Process
  results = {}
  db.models[:host].all.each do |host|
    groups = host.groups_dataset.map(:name)
    results[host[:name].to_sym] = {}
    results[host[:name].to_sym][:groups] = groups

    hostvars = {}
    host.hostvars_dataset.each do |hv|
      hostvars[hv[:name].to_sym] = hv[:value]
    end

    unless hostvars.empty?
      results[host[:name].to_sym][:hostvars] = hostvars
    end
  end
  fmt.dump(results)
end

#listvars(*argv) ⇒ Object



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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/moose_inventory/cli/host_listvars.rb', line 15

def listvars(*argv)
  # Convenience
  confopts = Moose::Inventory::Config._confopts

  # sanity
  if confopts[:ansible] == true
    if argv.length != 1
      abort('ERROR: Wrong number of arguments for Ansible mode, '\
            "#{args.length} for 1.")
    end
  else
    if argv.empty?
      abort('ERROR: Wrong number of arguments, '\
            "#{args.length} for 1 or more.")
    end
  end

  # Convenience
  db = Moose::Inventory::DB
  fmt = Moose::Inventory::Cli::Formatter

  # Arguments
  names = argv.uniq.map(&:downcase)

  # process
  results = {}

  if confopts[:ansible] == true
    # This is the implementation per Ansible specs
    name = names.first
    host = db.models[:host].find(name: name)
    if host.nil?
      fmt.warn "The host #{name} does not exist.\n"
    else
      host.hostvars_dataset.each do |hv|
        results[hv[:name].to_sym] = hv[:value]
      end
    end

    # Add the Ansible 1.3 '_meta' tag
    # see http://docs.ansible.com/ansible/developing_inventory.html#tuning-the-external-inventory-script
    results['_meta'.to_sym] = {}
    results['_meta'.to_sym]['hostvars'.to_sym] = {}
    db.models[:host].each do |host|
      results['_meta'.to_sym]['hostvars'.to_sym][host.name.to_sym] = {}
      host.hostvars_dataset.each do |hv|
        results['_meta'.to_sym]['hostvars'.to_sym][host.name.to_sym][hv[:name].to_sym] = hv[:value]
      end
    end

  else
    # This our more flexible implementation, which is not compatible
    # with the Ansible specs
    names.each do |name|
      host = db.models[:host].find(name: name)
      next if host.nil?
      results[name.to_sym] = {}
      host.hostvars_dataset.each do |hv|
        results[name.to_sym][hv[:name].to_sym] = hv[:value]
      end
    end
  end
  fmt.dump(results)
end

#rm(*argv) ⇒ Object

rubocop:disable Metrics/AbcSize



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
# File 'lib/moose_inventory/cli/host_rm.rb', line 16

def rm(*argv) # rubocop:disable Metrics/AbcSize
  #
  # Sanity
  if argv.empty?
    abort('ERROR: Wrong number of arguments, '\
      "#{argv.length} for 1 or more.")
  end

  # Convenience
  db = Moose::Inventory::DB
  fmt = Moose::Inventory::Cli::Formatter

  # Arguments
  names = argv.uniq.map(&:downcase)

  # Transaction
  warn_count = 0
  db.transaction do # Transaction start
    names.each do |name|
      puts "Remove host '#{name}':"
      fmt.puts 2, "- Retrieve host '#{name}'..."
      host = db.models[:host].find(name: name)
      if host.nil?
        warn_count += 1
        fmt.warn "Host '#{name}' does not exist, skipping.\n"
        fmt.puts 4, '- No such host, skipping.'
      end
      fmt.puts 4, '- OK'
      unless host.nil?
        fmt.puts 2, "- Destroy host '#{name}'..."
        host.remove_all_groups
        host.destroy
        fmt.puts 4, '- OK'
      end
      fmt.puts 2, '- All OK'
    end
  end # Transaction end
  if warn_count == 0
    puts 'Succeeded.'
  else
    puts 'Succeeded, with warnings.'
  end
end

#rmgroup(*args) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/moose_inventory/cli/host_rmgroup.rb', line 20

def rmgroup(*args)
  abort_if_missing_args(args, 2, '2 or more')

  name = args[0].downcase
  groups = normalize_names(args.slice(1, args.length - 1))

  abort_if_automatic_group(groups)

  context = Moose::Inventory::InventoryContext.new(db: db)
  operation = Moose::Inventory::Operations::RemoveAssociations.new(context: context)

  db.transaction do
    puts "Dissociate host '#{name}' from groups '#{groups.join(',')}':"
    host = fetch_existing_host_for_rmgroup(context, name)
    render_host_rmgroup_events(
      operation.host_from_groups(host: host, host_name: name, group_names: groups).events
    )
    fmt.puts 2, '- All OK'
  end
  puts 'Succeeded'
end

#rmvar(*args) ⇒ Object

rubocop:disable Metrics/LineLength



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
64
65
# File 'lib/moose_inventory/cli/host_rmvar.rb', line 16

def rmvar(*args) # rubocop:disable Metrics/AbcSize
  # rubocop:enableMetrics/LineLength
  if args.length < 2
    abort('ERROR: Wrong number of arguments, ' \
          "#{args.length} for 2 or more.")
  end

  # Convenience
  db  = Moose::Inventory::DB
  fmt = Moose::Inventory::Cli::Formatter

  # Arguments
  name = args[0].downcase
  vars = args.slice(1, args.length - 1).uniq

  # Transaction
  db.transaction do # Transaction start
    puts "Remove variable(s) '#{vars.join(',')}' from host '#{name}':"

    fmt.puts 2, "- retrieve host '#{name}'..."
    host = db.models[:host].find(name: name)
    if host.nil?
      fail db.exceptions[:moose],
           "The host '#{name}' does not exist."
    end
    fmt.puts 4, '- OK'

    hostvars_ds = host.hostvars_dataset
    vars.each do |v|
      fmt.puts 2, "- remove variable '#{v}'..."
      vararray = v.split('=')
      if v.start_with?('=') || v.scan('=').count > 1
        fail db.exceptions[:moose],
             "Incorrect format in {#{v}}. " \
             'Expected \'key\' or \'key=value\'.'
      end

      # Check against existing associations
      hostvar = hostvars_ds[name: vararray[0]]
      unless hostvar.nil?
        # remove the association
        host.remove_hostvar(hostvar)
        hostvar.destroy
      end
      fmt.puts 4, '- OK'
    end
    fmt.puts 2, '- all OK'
  end # Transaction end
  puts 'Succeeded.'
end