class Ansible::Inventory
Attributes
groups[R]
hosts[R]
Public Class Methods
new()
click to toggle source
# File lib/ansible/inventory.rb, line 86 def initialize @hosts = Host::Collection.new @groups = Group::Collection.new end
read_file(file)
click to toggle source
# File lib/ansible/inventory.rb, line 8 def read_file(file) inventory = Inventory.new last_group = nil in_vars = false in_children = false File.foreach(file) do |line| case when line =~ /^\s*#/ next # [group:vars] or [group:chidren] when line =~ /^\[\S+:(vars|children)\]$/ group_name, vars_or_children = line[/^\[(\S+)\]$/, 1].split(':') in_vars = vars_or_children == 'vars' in_children = vars_or_children == 'children' last_group = inventory.groups[group_name] || inventory.groups.add(group_name) # [group] when line =~ /^\[[^:]+\]$/ group_name = line[/^\[(\S+)\]$/, 1] last_group = inventory.groups.add(group_name) when line =~ /^\s*[^\[]\S+\s*(\S+=\S+\s*)*$/ host_name, *rest = line.split if in_children && rest.empty? child_group = inventory.groups[host_name] || inventory.groups.add(host_name) last_group.children << child_group.name elsif in_vars && host_name.index('=') && rest.empty? k, v = host_name.split('=', 2) last_group.vars[k] = v else vars = ActiveSupport::HashWithIndifferentAccess[rest.map {|s| s.split('=', 2)}] if last_group host = inventory.hosts.find {|h| h.name == host_name} || Host.new(host_name, vars) last_group.hosts << host else inventory.hosts.add host_name, vars end end end end inventory end
Public Instance Methods
write_file(file)
click to toggle source
# File lib/ansible/inventory.rb, line 50 def write_file(file) File.open(file, 'w') do |f| hosts.each {|host| f.puts ([host.name] + host.vars.map {|k, v| "#{k}=#{v}"}).join(' ') } groups.each {|group| unless group.hosts.empty? f.puts f.puts "[#{group.name}]" group.hosts.each {|host| if hosts.find {|h| h == host } f.puts host.name else f.puts ([host.name] + host.vars.map {|k, v| "#{k}=#{v}"}).join(' ') end } end unless group.vars.empty? f.puts f.puts "[#{group.name}:vars]" group.vars.each {|k, v| f.puts "#{k}=#{v}" } end unless group.children.empty? f.puts f.puts "[#{group.name}:children]" group.children.each {|s| f.puts s} end } end end