Module: Ansible::Methods

Included in:
Ansible, AdHoc
Defined in:
lib/ansible/ad_hoc.rb

Overview

Ansible Ad-Hoc methods

Constant Summary collapse

BIN =

executable that runs Ansible Ad-Hoc commands

'ansible'

Instance Method Summary collapse

Instance Method Details

#list_hosts(cmd) ⇒ String

Ask Ansible to list hosts

Examples:

List hosts with an inline inventory that only contains localhost

list_hosts 'all -i localhost,'

Parameters:

  • cmd (String)

    the Ansible command to execute

Returns:

  • (String)

    the output



26
27
28
29
# File 'lib/ansible/ad_hoc.rb', line 26

def list_hosts(cmd)
  output = one_off("#{cmd} --list-hosts").gsub!(/\s+hosts.*:\n/, '').strip
  output.split("\n").map(&:strip)
end

#one_off(cmd) ⇒ String Also known as: []

Run an Ad-Hoc Ansible command

Examples:

Run a simple shell command with an inline inventory that only contains localhost

one_off 'all -c local -a "echo hello"'

Parameters:

  • cmd (String)

    the Ansible command to execute

Returns:

  • (String)

    the output



15
16
17
18
# File 'lib/ansible/ad_hoc.rb', line 15

def one_off(cmd)
  # TODO if debug then puts w/ colour
  `#{config.to_s "#{BIN} #{cmd}"}`
end

#parse_host_vars(host, inv, filter = 'hostvars[inventory_hostname]') ⇒ Hash

Fetches host variables via Ansible’s debug module

Examples:

List variables for localhost

parse_host_vars 'localhost', 'localhost,'

Parameters:

  • host (String)

    the <host-pattern> for target host(s)

  • inv (String)

    the inventory host path or comma-separated host list

  • filter (String) (defaults to: 'hostvars[inventory_hostname]')

    the variable filter

Returns:

  • (Hash)

    the variables pertaining to the host



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/ansible/ad_hoc.rb', line 38

def parse_host_vars(host, inv, filter = 'hostvars[inventory_hostname]')
  cmd = "all -m debug -a 'var=#{filter}' -i #{inv} -l #{host}"
  json = self[cmd].split(/>>|=>/).last

  # remove any colour added to console output
  # TODO move to Output module as #bleach, perhaps use term-ansicolor
  # possibly replace regexp with /\e\[(?:(?:[349]|10)[0-7]|[0-9]|[34]8;5;\d{1,3})?m/
  # possibly use ANSIBLE_NOCOLOR? or --nocolor
  json = json.strip.chomp.gsub(/\e\[[0-1][;]?(3[0-7]|90|1)?m/, '')

  hostvars = JSON.parse(json)

  hostvars[filter]
end