Puppet Function: agent_key

Defined in:
lib/puppet/parser/functions/agent_key.rb
Function type:
Ruby 3.x API

Overview

agent_key()Any

Returns:

  • (Any)


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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/puppet/parser/functions/agent_key.rb', line 7

newfunction(:agent_key, :type => :rvalue) do |args|
    token = args[0]
    agent_key = args[1]
    server_name = args[2]
    group = args[3]
    use_fqdn = args[4]

    unless agent_key.nil? or agent_key.empty?
        notice ["Agent Key Provided: #{ agent_key }"]
        return agent_key
    end

    hostname = lookupvar("hostname")
    fqdn = lookupvar("fqdn")
    provider = lookupvar('sd_provider')
    provider_id = lookupvar('sd_provider_id')
    project_id = lookupvar('sd_project_id')

    if server_name.nil? or server_name.empty?
        server_name = fqdn
    end

    if use_fqdn
        notice "Using fqdn for hostname"
        hostname = fqdn
        checks = [hostname]
    else
        # if we don't explicitly want to use the fqdn
        # then we should check hostname and fqdn
        checks = [hostname, fqdn]
    end


    notice ["Server Name: #{ server_name }"]

    # can we get the agent key from the environment
    # we set it on cloud devices created on Amazon or Rackspace
    # created via the serverdensity UI
    # uses custom agent_key fact
    agent_key = lookupvar("sd_agent_key")

    # lookupvar returns undef if no value
    # test against nil just in case
    unless agent_key.nil? or agent_key == :undefined or agent_key == :undef
        notice ["Agent Key Provided via Facter: #{ agent_key }"]
        return agent_key
    end

    if agent_key == :undef
        agent_key = ""
    end

    notice ["Using SD Version 2"]

    base_url = "https://api.serverdensity.io"

    list = nil
    if provider and provider_id
        # attempt to find the device by providerId
        filter = {
            'type' => 'device',
            'provider' => provider,
            'providerId' => provider_id
        }
        if project_id
            filter['projectId'] = project_id
        end
        notice ["Making API request for provider: #{ provider } and providerId: #{ provider_id }"]
        filter_json = URI.escape(PSON.dump(filter))
        begin
            uri = URI("#{ base_url }/inventory/devices?filter=#{ filter_json }&token=#{ token }")
            req = Net::HTTP::Get.new(uri.request_uri)
            https = Net::HTTP.new(uri.host, uri.port)
            https.use_ssl = true
            https.verify_mode = OpenSSL::SSL::VERIFY_NONE
            res = https.start { |cx| cx.request(req) }

            list = PSON.parse(res.body)

        rescue
            err ["Error from SD API, stopping run"]
            raise Puppet::ParseError, "Error from SD API"
        end

        if Integer(res.code) >= 500
            err ["Error from SD API, stopping run"]
            raise Puppet::ParseError, "Error from SD API"
        end

    end

    if list.nil? or list.empty?
        # attempt to find the device by hostname (which may be local or FQDN)
        list = nil
        checks.each do |hn|
            # attempt to detect google cloud devices
            if provider == 'google'
                hn_split=hn.split(".")
                name=hn_split[0..-4].join('.')
                filter = {
                    'type' => 'device',
                    'deleted' => false,
                    'name' => name,
                    'projectId' => project_id,
                    'provider' => 'google'
                }
            else
                filter = {
                    'type' => 'device',
                    'deleted' => false,
                    'hostname' => hn,
                }
            end

            filter_json = URI.escape(PSON.dump(filter))

            notice ["Making API request for hostname: #{ hn }"]

            begin
                uri = URI("#{ base_url }/inventory/devices?filter=#{ filter_json }&token=#{ token }")
                req = Net::HTTP::Get.new(uri.request_uri)
                https = Net::HTTP.new(uri.host, uri.port)
                https.use_ssl = true
                https.verify_mode = OpenSSL::SSL::VERIFY_NONE
                res = https.start { |cx| cx.request(req) }

                list = PSON.parse(res.body)

            rescue
                err ["Error from SD API, stopping run"]
                raise Puppet::ParseError, "Error from SD API"
            end

            if Integer(res.code) >= 500
                err ["Error from SD API, stopping run"]
                raise Puppet::ParseError, "Error from SD API"
            end

            if list.length > 0
                # keep this response -- device was found
                break
            end
        end
    end

    if Integer(res.code) >= 300 or list.length == 0
        notice ["Device not found, creating a new one"]

        data = {
            :name => server_name,
            :hostname => hostname,
        }
        unless group.nil? or group.empty?
            data['group'] = group
        end

        if ["amazon", "google", "rackspace"].include?(provider)
            data['provider'] = provider
            if provider_id
                data['providerId'] = provider_id
            end
            if project_id
                data['projectId'] = project_id
            end
        end

        uri = URI("#{ base_url }/inventory/devices?token=#{ token }")
        req = Net::HTTP::Post.new(uri.request_uri)

        # Create new device
        req.set_form_data(data)

        https = Net::HTTP.new(uri.host, uri.port)
        https.use_ssl = true
        https.verify_mode = OpenSSL::SSL::VERIFY_NONE
        res = https.start { |cx| cx.request(req) }

        if Integer(res.code) >= 500
            err ["Error from SD API, stopping run"]
            raise Puppet::ParseError, "Error from SD API"
        end

        device = PSON.parse(res.body)
    elsif list.length > 1
        fail ["More than one existing device matches this hostname or fqdn. Please manually set token"]
    else
        device = list[0]

        # Has the group changed?
        existing_group = device["group"]

        if existing_group != group
            notice ["Updating group on #{device['_id']} from #{existing_group} to #{group}"]

            # update the group
            uri = URI("#{ base_url }/inventory/devices/#{ device['_id'] }?token=#{ token }")

            req = Net::HTTP::Put.new(uri.request_uri)

            update_data = {
                :group => group
            }
            req.set_form_data(update_data)
            https = Net::HTTP.new(uri.host, uri.port)
            https.use_ssl = true
            https.verify_mode = OpenSSL::SSL::VERIFY_NONE
            res = https.start { |cx| cx.request(req) }

        end
    end

    agent_key = device["agentKey"]

    notice ["Agent Key: #{ agent_key }"]
    return agent_key
end