summaryrefslogtreecommitdiffstats
path: root/lib/puppet/provider/host/parsed.rb
blob: d69dcbec46192a8c5ec95cf28e0f200ee5b12a20 (plain)
1
2
3
4
5
6
7
8
9
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
64
65
66
67
68
69
70
71
72
73
74
require 'puppet/provider/parsedfile'

hosts = nil
case Facter.value(:operatingsystem)
when "Solaris"; hosts = "/etc/inet/hosts"
else
    hosts = "/etc/hosts"
end

Puppet::Type.type(:host).provide(:parsed,
    :parent => Puppet::Provider::ParsedFile,
    :default_target => hosts,
    :filetype => :flat
) do
    confine :exists => hosts

    text_line :comment, :match => /^#/
    text_line :blank, :match => /^\s*$/

    record_line :parsed, :fields => %w{ip name host_aliases},
        :optional => %w{host_aliases},
        :rts => true do |line|
        hash = {}
        if line.sub!(/^(\S+)\s+(\S+)\s*/, '')
            hash[:ip] = $1
            hash[:name] = $2

            if line.empty?
                hash[:host_aliases] = []
            else
                line.sub!(/\s*/, '')
                line.sub!(/^([^#]+)\s*/) do |value|
                    aliases = $1
                    unless aliases =~ /^\s*$/
                        hash[:host_aliases] = aliases.split(/\s+/)
                    end

                    ""
                end
            end
        else
            raise Puppet::Error, "Could not match '%s'" % line
        end

        if hash[:host_aliases] == ""
            hash[:host_aliases] = []
        end

        return hash
    end

    # Convert the current object into a host-style string.
    def self.to_line(hash)
        return super unless hash[:record_type] == :parsed
        [:ip, :name].each do |n|
            unless hash[n] and hash[n] != :absent
                raise ArgumentError, "%s is a required attribute for hosts" % n
            end
        end

        str = "%s\t%s" % [hash[:ip], hash[:name]]

        if hash.include? :host_aliases and !hash[:host_aliases].empty?
            if hash[:host_aliases].is_a? Array
                str += "\t%s" % hash[:host_aliases].join("\t")
            else
                raise ArgumentError, "Host aliases must be specified as an array"
            end
        end

        str
    end
end