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
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2019 Red Hat Inc.
# Copyright (C) 2021 Western Telematic Inc.
#
# GNU General Public License v3.0+
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
# Module to execute WTI hostname parameters from WTI OOB and PDU devices.
# CPM remote_management
#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = """
---
module: cpm_hostname_config
version_added: "2.11.0"
author:
- "Western Telematic Inc. (@wtinetworkgear)"
short_description: Set Hostname (Site ID), Location, Asset Tag parameters in WTI OOB and PDU devices.
description:
- "Set Hostname (Site ID), Location, Asset Tag parameters parameters in WTI OOB and PDU devices"
options:
cpm_url:
description:
- This is the URL of the WTI device to send the module.
type: str
required: true
cpm_username:
description:
- This is the Username of the WTI device to send the module.
type: str
required: true
cpm_password:
description:
- This is the Password of the WTI device to send the module.
type: str
required: true
use_https:
description:
- Designates to use an https connection or http connection.
type: bool
required: false
default: true
validate_certs:
description:
- If false, SSL certificates will not be validated. This should only be used
- on personally controlled sites using self-signed certificates.
type: bool
required: false
default: true
use_proxy:
description:
- Flag to control if the lookup will observe HTTP proxy environment variables when present.
type: bool
required: false
default: false
hostname:
description:
- This is the Hostname (Site-ID) tag to be set for the WTI OOB and PDU device.
type: str
required: false
location:
description:
- This is the Location tag to be set for the WTI OOB and PDU device.
type: str
required: false
assettag:
description:
- This is the Asset Tag to be set for the WTI OOB and PDU device.
type: str
required: false
notes:
- Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.
"""
EXAMPLES = """
# Set Hostname, Location and Site-ID variables of a WTI device
- name: Set known fixed hostname variables of a WTI device
cpm_time_config:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
hostname: "myhostname"
location: "Irvine"
assettag: "irvine92395"
# Set the Hostname variable of a WTI device
- name: Set the Hostname of a WTI device
cpm_time_config:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
hostname: "myhostname"
"""
RETURN = """
data:
description: The output JSON returned from the commands sent
returned: always
type: complex
contains:
timestamp:
description: Current timestamp of the WTI device after module execution.
returned: success
type: str
sample: "2021-08-17T21:33:50+00:00"
hostname:
description: Current Hostname (Site-ID) of the WTI device after module execution.
returned: success
type: str
sample: "myhostname"
location:
description: Current Location of the WTI device after module execution.
returned: success
type: int
sample: "Irvine"
assettag:
description: Current Asset Tag of the WTI device after module execution.
returned: success
type: int
sample: "irvine92395"
"""
import base64
import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_text, to_bytes, to_native
from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError
from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError
def assemble_json(cpmmodule, existing):
total_change = 0
json_load = ietfstring = ""
localhostname = locallocation = localassettag = None
if cpmmodule.params["hostname"] is not None:
if (existing["unitid"]["hostname"] != to_native(cpmmodule.params["hostname"])):
total_change = (total_change | 1)
localhostname = to_native(cpmmodule.params["hostname"])
if cpmmodule.params["location"] is not None:
if (existing["unitid"]["location"] != to_native(cpmmodule.params["location"])):
total_change = (total_change | 2)
locallocation = to_native(cpmmodule.params["location"])
if cpmmodule.params["assettag"] is not None:
if (existing["unitid"]["assettag"] != to_native(cpmmodule.params["assettag"])):
total_change = (total_change | 4)
localassettag = to_native(cpmmodule.params["assettag"])
if (total_change > 0):
protocol = protocolchanged = 0
ietfstring = ""
if (localhostname is not None):
ietfstring = '%s"hostname": "%s"' % (ietfstring, localhostname)
if (locallocation is not None):
if (len(ietfstring) > 0):
ietfstring = '%s,' % (ietfstring)
ietfstring = '%s"location": "%s"' % (ietfstring, locallocation)
if (localassettag is not None):
if (len(ietfstring) > 0):
ietfstring = '%s,' % (ietfstring)
ietfstring = '%s"assettag": "%s"' % (ietfstring, localassettag)
json_load = '{"unitid": {'
json_load = '%s%s' % (json_load, ietfstring)
json_load = '%s}}' % (json_load)
else:
json_load = None
return json_load
def run_module():
# define the available arguments/parameters that a user can pass to
# the module
module_args = dict(
cpm_url=dict(type='str', required=True),
cpm_username=dict(type='str', required=True),
cpm_password=dict(type='str', required=True, no_log=True),
hostname=dict(type='str', required=False, default=None),
location=dict(type='str', required=False, default=None),
assettag=dict(type='str', required=False, default=None),
use_https=dict(type='bool', default=True),
validate_certs=dict(type='bool', default=True),
use_proxy=dict(type='bool', default=False)
)
result = dict(
changed=False,
data=''
)
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])),
errors='surrogate_or_strict')))
if module.params['use_https'] is True:
protocol = "https://"
else:
protocol = "http://"
fullurl = ("%s%s/api/v2/config/hostname" % (protocol, to_native(module.params['cpm_url'])))
method = 'GET'
try:
response = open_url(fullurl, data=None, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'],
headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth})
except HTTPError as e:
fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
except URLError as e:
fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
except SSLValidationError as e:
fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
except ConnectionError as e:
fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
result['data'] = response.read()
payload = assemble_json(module, json.loads(result['data']))
if module.check_mode:
if payload is not None:
result['changed'] = True
else:
if payload is not None:
fullurl = ("%s%s/api/v2/config/hostname" % (protocol, to_native(module.params['cpm_url'])))
method = 'POST'
try:
response = open_url(fullurl, data=payload, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'],
headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth})
except HTTPError as e:
fail_json = dict(msg='POST: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
except URLError as e:
fail_json = dict(msg='POST: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
except SSLValidationError as e:
fail_json = dict(msg='POST: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
except ConnectionError as e:
fail_json = dict(msg='POST: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
result['changed'] = True
result['data'] = json.loads(response.read())
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
|