forked from jdchaiken/solarwinds-Node_Module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorion_node.py
573 lines (500 loc) · 18.1 KB
/
orion_node.py
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Jarett D. Chaiken <[email protected]>
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community',
}
DOCUMENTATION = '''
---
module: orion_node
short_description: Created/Removes/Edits Nodes in Solarwinds Orion NPM
description:
- "Create/Remove Nodes in Orion NPM"
version_added: "2.7"
author: "Jarett D Chaiken (@jdchaiken)"
options:
hostname:
description:
- Name of Orion host running SWIS service
required: true
username:
description:
- Orion Username
- Active Directory users must use DOMAIN\\username format
required: true
password:
description:
- Password for Orion user
required: true
state:
description:
- The desired state of the node
required: false
choices:
- present
- absent
- remanaged
- unmanaged
- muted
- unmuted
default:
- managed
node_id:
description:
- node_id of the node
- Must provide either an IP address, node_id, or exact node name
required: false
name:
description:
- Name of the node
- For Adding a node this field is required
- For All other states field is optional and partial names are acceptable
required: false
ip_address:
description:
- IP Address of the node
- Must provide either an IP address, node_id, or exact node name
required: false
unmanage_from:
description:
- "The date and time (in ISO 8601 UTC format) to begin the unmanage period."
- If this is in the past, the node will be unmanaged effective immediately.
- If not provided, module defaults to now.
- "ex: 2017-02-21T12:00:00Z"
required: false
unmanage_until:
description:
- "The date and time (in ISO 8601 UTC format) to end the unmanage period."
- You can set this as far in the future as you like.
- If not provided, module defaults to 24 hours from now.
- "ex: 2017-02-21T12:00:00Z"
required: false
polling_method:
description:
- Polling method to use
choices:
- external_node
- icmp
- snmp
- WMI
- agent
- vcenter
- meraki
default: snmp
required: false
ro_community_string:
description:
- SNMP Read-Only Community string
- "Note: Required if using snmp polling"
required: false
rw_community_string:
description:
- SNMP Read-Write Community string
required: false
snmp_version:
description:
- SNMPv2c is used by default
- SNMPv3 not supported at this time
choices:
- 2
default: 'snmpv2c'
requried: false
snmp_port:
description:
- port that SNMP server listens on
required: false
default: '161'
snmp_allow_64:
description:
- Set true if device supports 64-bit counters
type: bool
default: true
required: false
wmi_credential:
description:
- 'Credential Name already configured in NPM Found under "Manage Windows Credentials" section of the Orion website (Settings)'
- "Note: creation of credentials are not supported at this time"
- Required if using WMI polling
required: false
polling_engine:
description:
- ID of polling engine that NPM will use to poll this device
required: false
custom_properties:
description:
- A list of custom properties and their values
required: false
requirements:
- orionsdk
- datetime
- requests
- traceback
'''
EXAMPLES = '''
---
- name: Remove a node from Orion
orion_node:
hostname: "<Hostname of orion server>"
username: Orion Username
password: Orion Password
name: servername
state: absent
- name: Mute hosts
hosts: all
gather_facts: no
tasks:
- orion_node:
hostname: "{{solarwinds_host}}"
username: "{{solarwinds_username}}"
password: "{{solarwinds_password}}"
name: "{{inventory_hostname}}"
state: muted
unmanage_from: "2020-03-13T20:58:22.033"
unmanage_until: "2020-03-14T20:58:22.033"
delegate_to: localhost
'''
import traceback
from datetime import datetime, timedelta
import string
import re
from dateutil.parser import parse
import requests
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
try:
from orionsdk import SwisClient
HAS_ORION = True
except Exception as e:
HAS_ORION = False
__SWIS__ = None
requests.urllib3.disable_warnings()
def run_module():
'''
Module Main Function
'''
global __SWIS__
module_args = {
'hostname': {'required': True},
'username': {'required': True, 'no_log': True},
'password': {'required': True, 'no_log': True},
'state': {
'required': False,
'choices': [
'present',
'absent',
'remanaged',
'unmanaged',
'muted',
'unmuted',
],
'default': 'managed'
},
'node_id': {'required': False},
'ip_address': {'required': False},
'name': {'required': False},
'unmanage_from': {'required': False, 'default': "None"},
'unmanage_until': {'required': False, 'default': "None"},
'polling_method': {
'required': False,
'choices': [
'External',
'ICMP',
'SNMP',
'WMI',
'Agent'],
'default': 'SNMP'
},
'ro_community_string': {'required': False, 'no_log': True},
'rw_community_string': {'required': False, 'no_log': True},
'snmp_version': {'required': False, 'default': '2'},
'snmp_port': {'required': False, 'default': '161'},
'snmp_allow_64': {'required': False, 'default': True},
'wmi_credential': {'required': False, 'no_log': True},
'polling_engine': {'required': False},
'custom_properties': {'required': False, 'default': {}}
}
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
if not HAS_ORION:
module.fail_json(msg='orionsdk required for this module')
options = {
'hostname': module.params['hostname'],
'username': module.params['username'],
'password': module.params['password'],
}
__SWIS__ = SwisClient(**options)
try:
__SWIS__.query('SELECT uri FROM Orion.Environment')
except Exception as e:
module.fail_json(
msg='Failed to query Orion. '
'Check Hostname, Username, and/or Password: {0}'.format(str(e))
)
if module.params['state'] == 'present':
add_node(module)
elif module.params['state'] == 'absent':
remove_node(module)
elif module.params['state'] == 'remanaged':
remanage_node(module)
elif module.params['state'] == 'unmanaged':
unmanage_node(module)
elif module.params['state'] == 'muted':
mute_node(module)
elif module.params['state'] == 'unmuted':
unmute_node(module)
def _get_node(module):
node = {}
if module.params['node_id'] is not None:
results = __SWIS__.query(
'SELECT NodeID, Caption, Unmanaged, UnManageFrom, UnManageUntil, Uri FROM Orion.Nodes WHERE NodeID = '
'@node_id',
node_id=module.params['node_id']
)
elif module.params['ip_address'] is not None:
results = __SWIS__.query(
'SELECT NodeID, Caption, Unmanaged, UnManageFrom, UnManageUntil, Uri FROM Orion.Nodes WHERE IPAddress = '
'@ip_address',
ip_address=module.params['ip_address']
)
elif module.params['name'] is not None:
results = __SWIS__.query(
"SELECT NodeID, Caption, Unmanaged, UnManageFrom, UnManageUntil, Uri "
"FROM Orion.Nodes WHERE Caption like "
"@name",
name='%'+module.params['name']+'%'
)
else:
# No Id provided
module.fail_json(msg='You must provide either a node_id, ip_address, or name')
if results['results']:
node['nodeid'] = results['results'][0]['NodeID']
node['caption'] = results['results'][0]['Caption']
node['netobjectid'] = 'N:{}'.format(node['nodeid'])
node['unmanaged'] = results['results'][0]['Unmanaged']
node['unmanagefrom'] = parse(results['results'][0]['UnManageFrom']).isoformat()
node['unmanageuntil'] = parse(results['results'][0]['UnManageUntil']).isoformat()
node['uri'] = results['results'][0]['Uri']
return node
def _validate_fields(module):
# Setup properties for new node
props = {
'IPAddress': module.params['ip_address'],
'Caption': module.params['name'],
'ObjectSubType': module.params['polling_method'].upper(),
'Community': module.params['ro_community_string'],
'RWCommunity': module.params['rw_community_string'],
'SNMPVersion': module.params['snmp_version'],
'AgentPort': module.params['snmp_port'],
'Allow64BitCounters': module.params['snmp_allow_64'],
'EngineID': module.params['polling_engine'],
'External': lambda x: True if module.params['polling_method'] =='EXTERNAL' else False,
'State': module.params['state'],
}
# Validate required fields
if not props['IPAddress']:
module.fail_json(msg='IP Address Parameter is required')
if not props['External']:
if not props['Caption']:
module.fail_json(msg='Node name is required to add a node')
if not props['ObjectSubType']:
module.fail_json(msg='Polling Method is required [External, SNMP, ICMP, WMI, Agent]')
elif props['ObjectSubType'] == 'SNMP':
if not props['Community']:
module.fail_json(msg='Read-Only Community String is required')
elif props['ObjectSubType'] == 'WMI':
if not props['wmi_credential']:
module.fail_json(msg='WMI Credential is required')
elif props['ObjectSubType'] == 'EXTERNAL':
props['ObjectSubType'] = 'ICMP'
if not props['SNMPVersion']:
props['SNMPVersion'] = 2
if not props['AgentPort']:
props['AgentPort'] = 161
if not props['Allow64BitCounters']:
props['Allow64BitCounters'] = True
if not props['EngineID']:
props['EngineID'] = 1
if props['State'] == 'present':
if not props['name']:
module.fail_json(msg='Node name is required')
return props
def _add_wmi_credentials(module, node, **props):
# Check if passed credential is valid
cred = __SWIS__.query(
"SELECT ID FROM Orion.Credential WHERE Name = "
"@wmi_credential",
wmi_credential= module.params['wmi_credential'])
if cred['ID']: # Valid credential passed - Add to Orion.NodeSettings
nodesettings = {
'nodeid': node['nodeid'],
'SettingName': 'WMICredential',
'SettingValue': str(cred['ID']),
}
__SWIS__.create('Orion.NodeSettings', **nodesettings)
else: # Invalid Credential
module.fail_json(msg='Invalid Credential id {0}'.format(module.params['wmi_credential']), **cred)
def _add_pollers(module, node, external):
pollers_enabled = {
'N.Status.ICMP.Native': True,
'N.Status.SNMP.Native': False,
'N.ResponseTime.ICMP.Native': True,
'N.ResponseTime.SNMP.Native': False,
'N.Details.SNMP.Generic': True,
'N.Uptime.SNMP.Generic': True,
'N.Cpu.SNMP.HrProcessorLoad': True,
'N.Memory.SNMP.NetSnmpReal': True,
'N.AssetInventory.Snmp.Generic': True,
'N.Topology_Layer3.SNMP.ipNetToMedia': False,
'N.Routing.SNMP.Ipv4CidrRoutingTable': False
}
if not external:
pollers = []
for k in pollers_enabled:
pollers.append(
{
'PollerType': k,
'NetObject': 'N:' + node['nodeid'],
'NetObjectType': 'N',
'NetObjectID': node['nodeid'],
'Enabled': pollers_enabled[k]
}
)
for poller in pollers:
print("Adding poller type: {} with status {}...".format(poller['PollerType'], poller['Enabled']), end="")
try:
__SWIS__.create('Orion.Pollers', **poller)
except Exception:
module.fail_json(**poller)
def add_node(module):
# Check if node already exists
node = _get_node(module)
if node:
module.exit_json(changed=False, ansible_facts=node)
## Validate Fields
props = _validate_fields(module)
# Add Node
try:
__SWIS__.create('Orion.Nodes', **props)
node['changed'] = True
except Exception as e:
module.fail_json(msg='Failed to add {}'.format(str(e)), **props)
#### If Node is a WMI node, assign credential
if props['ObjectSubType'] == 'WMI':
_add_wmi_credentials(module, node, **props)
## Add Pollers
_add_pollers(module, node, lambda x: True if props['External'] else False)
## Add Custom Properties
custom_properties = lambda x: module.params['custom_properties'] if module.params['custom_properties'] else {},
if not props['External']:
try:
node = _get_node(module)
except Exception as e:
module.fail_json(msg='Error adding Custom properties {}'.format(str(e)))
if type(custom_properties) is dict:
for k in custom_properties.keys():
try:
__SWIS__.update(node['Uri'] + '/CustomProperties', k=custom_properties[k])
module.exit_json(mgs="{0} has been added".format(node['caption']), **node)
except Exception as e:
module.fail_json(msg='Failed to add custom properties',**node)
module.exit_json()
def remove_node(module):
node = _get_node(module)
if not node:
module.exit_json(changed=False)
try:
__SWIS__.delete(node['uri'])
node['changed'] = True
module.exit_json(**node)
except Exception as e:
module.fail_json(msg='Error removing node {}'.format(str(e)), **node)
def remanage_node(module):
node = _get_node(module)
if not node:
module.fail_json(skipped=True, msg='Node not found')
elif not node['unmanaged']:
module.fail_json(changed=False)
try:
__SWIS__.invoke('Orion.Nodes', 'Remanage', node['netobjectid'])
module.exit_json(changed=True, msg="{0} has been remanaged".format(node['caption']))
except Exception as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
def unmanage_node(module):
now = datetime.utcnow()
tomorrow = now + timedelta(days=1)
node = _get_node(module)
unmanage_from = module.params['unmanage_from']
unmanage_until = module.params['unmanage_until']
if not unmanage_from:
unmanage_from = now
if not unmanage_until:
unmanage_until = tomorrow
if not node:
module.fail_json(skipped=True, msg='Node not found')
elif node['unmanaged']:
if unmanage_from == node['unManageFrom'] and unmanage_until == node['unManageUntil']:
module.exit_json(changed=False)
try:
__SWIS__.invoke(
'Orion.Nodes',
'Unmanage',
node['netobjectid'],
unmanage_from,
unmanage_until,
False # use Absolute Time
)
msg = "{0} will be unmanaged from {1} until {2}".format(
node['nodeid'],
unmanage_from,
unmanage_until
)
module.exit_json(changed=True, msg=msg)
except Exception as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
def mute_node(module):
now = datetime.now()
tomorrow = now + timedelta(days=1)
#Check if Node exists
node = _get_node(module)
if not node:
module.exit_json(skipped=True, msg='Node not found')
unmanage_from = module.params['unmanage_from']
unmanage_until = module.params['unmanage_until']
if unmanage_from == "None":
unmanage_from = now
if unmanage_until == "None":
unmanage_until = tomorrow
# Check if already muted
suppressed = __SWIS__.invoke('Orion.AlertSuppression','GetAlertSuppressionState',[node['uri']])[0]
# If already muted, exit
if suppressed['SuppressedFrom'] == unmanage_from and suppressed['SuppressedUntil'] == unmanage_until:
node['changed']=False
module.exit_json(changed=False, ansible_facts=node)
# Otherwise Mute Node with given parameters
try:
__SWIS__.invoke('Orion.AlertSuppression', 'SuppressAlerts', [node['uri']], unmanage_from, unmanage_until)
node['changed'] = True
module.exit_json(changed=True, ansible_facts=node)
except Exception as e:
#module.fail_json(msg="Unable to mute {0}".format(node['caption']), ansible_facts=node)
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
def unmute_node(module):
node = _get_node(module)
if not node:
module.exit_json(skipped=True, msg='Node not found')
# Check if already muted
suppressed = __SWIS__.invoke('Orion.AlertSuppression','GetAlertSuppressionState',[node['uri']])[0]
if suppressed['SuppressionMode'] == 0:
node['changed'] = False
module.exit_json(changed=False, ansible_facts=node)
else:
__SWIS__.invoke('Orion.AlertSuppression', 'ResumeAlerts',[node['uri']])
node['changed'] = True
module.exit_json(changed=True, ansible_facts=node)
def main():
run_module()
if __name__ == "__main__":
main()