-
Notifications
You must be signed in to change notification settings - Fork 4
/
nodeping.py
858 lines (765 loc) · 28.4 KB
/
nodeping.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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright: (c) 2024, NodePing LLC <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
import inspect
import traceback
from time import time
from ansible.module_utils.basic import AnsibleModule
ANSIBLE_METADATA = {
"metadata_version": "3.0",
"status": ["stableinterface"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: nodeping
short_description: Manage your NodePing checks
version_added: "2.5"
description:
- This module will let you get, create, update, or delete checks on your NodePing account
requirements:
- "The NodePing Python library: https://github.com/NodePing/nodepingpy"
options:
token:
description:
- Your API token for your NodePing account
type: str
customerid:
description:
- The ID for your subaccount
type: str
checktype:
description:
- The type of check that will be created
- Examples include PING, HTTP, SSL, DNS
type: str
checkid:
description:
- The ID of an already existing check
type: str
label:
description:
- The name you choose for your check
type: str
target:
description:
- URL or FQDN for check target
type: str
action:
description:
- Whether you want to get, create, update, or delete an existing check
- With getting, updating, and deleting checks, you will have to supply a checkid
choices: [ get, create, update, delete ]
type: str
required: true
interval:
description:
- How often this check runs in minutes
type: int
default: 15
enabled:
description:
- If the check should be enabled or not
type: bool
default: yes
public:
description:
- If yes public reports will be enabled for this check
type: bool
default: no
runlocations:
description:
- Which region to run your checks from
- type: str
- choices: [ nam, eur, eao, lam, wlw ]
type: str
homeloc:
description:
- Which probe to run your check from (Provider plan only)
- A list of probes can be found here https://nodeping.com/faq.html
- Use the abbreviation (such as WA for Seattle, WA location)
type: str
threshold:
description:
- the timeout for this check in seconds
default: 5
type: int
sens:
description:
- number of rechecks before this check is considered 'down' or 'up'
default: 2
type: int
dep:
description:
- the id of the check used for the notification dependency
type: str
mute:
description:
- optional boolean or millisecond timestamp or day (D), hour (H), minutes (M) or seconds (S) mute from now
- True mutes all notifications
- 5D = 5 day mute, 3H = 3 hour mute, 30M = 30 minute mute, 180S = 180 second mute
default: false
type: str
description:
description:
- optional string. Can put arbitrary text, JSON, XML, etc. Size limit 1000 characters
type: str
checktoken:
description:
- read-only field on PUSH checks
- Can reset this token by setting this value to 'reset'
type: str
clientcert:
description:
- specify the ID of a client certificate/key to be used in the DOHDOT check
type: str
contentstring:
description:
- The string to match the response against.
- For DNS, HTTPCONTENT, HTTPADV, FTP, SSH, WEBSOCKET, WHOIS type checks
type: str
dohdot:
description:
- string used to specify if DoH or DoT in the DOHDOT check.
default: doh
type: str
dnssection:
description:
- case-sensitive string for which section of the DNS reply to look in for the contentstring match
- values: answer, authority, additional, edns_options
default: answer
type: str
dnstype:
description:
- Optional string for DNS checks to indicate the type of DNS entry to query
- String set to one of: 'ANY', 'A', 'AAAA', 'CNAME', 'MX, 'NS, 'PTR', 'SOA', 'TXT'.
type: str
dnstoresolve:
description:
- optional string for DNS type checks - The FQDN of the DNS query
type: str
dnsrd:
description:
- optional boolean for DNS RD (Recursion Desired) bit.
- If you're using CloudFlare DNS servers, set this to no.
default: yes
type: bool
transport:
description:
- optional string for DNS transport protocol
type: str
default: udp
choices: [ tcp, udp ]
follow:
description:
- Used for HTTP, HTTPCONTENT and HTTPADV checks.
- If true, the check will follow up to four redirects
- The HTTPADV check only supports follow for GET requests.
type: bool
email:
description:
- Used for IMAP and SMTP checks.
type: str
port:
description:
- Required integer for DNS, FTP, NTP, PORT, SSH type checks.
- Used for check types that support port fields separate from the target address.
- HTTP and HTTPCONTENT will ignore this field as the port must be set in the target in standard URL format.
type: int
username:
description:
- String used for FTP, IMAP, POP, SMTP and SSH type checks.
- HTTP and HTTPCONTENT will ignore this field as the username must be set in the target in standard URL format.
type: str
password:
description:
- String used for FTP, IMAP, POP, SMTP and SSH type checks.
- Note that this is going to be passed back and forth in the data, so you should always be sure that credentials used for checks are very limited in their access level.
type: str
query:
description:
- optional string for PGSQL and MYSQL check types. SQL query to send to the database server
type: str
secure:
description:
- Specify whether the IMAP, SMTP, and POP checks should use TLS for the check.
type: bool
sshkey:
description:
- specify the ID of an SSH private key to be used in the SSH check
type: str
verify:
description:
- Set whether or not to verify the certificate
type: bool
hosts:
description:
- Object for specifying host information for the redis check
- Example: "hosts": {"HSGWNS": {"host": "redis1.example.com", "port": 6379}}
type: dict
ignore:
description:
- Optional string for the RBL check type, specifies RBL lists to ignore.
- Multiple lists can be added to be ignored.
type: str
invert:
description:
- Optional string for FTP, HTTPCONTENT, HTTPADV, NTP, PORT, SSH type checks
- Used for 'Does not contain' functionality in checks.
default: no
type: bool
warningdays:
description:
- Optional integer for SSL, WHOIS, POP, IMAP, and SMTP checks
- Number of days before certificate (or domain for WHOIS) expiration to fail the check and send a notification.
type: int
fields:
description:
- optional object used for fields to parse from the HTTPADV, HTTPPARSE, and SNMP response.
- This is a keyed list of fields, with an arbitrary (by default random) string as the key.
- Each object in the list should include three elements: name, min and max.
type: dict
postdata:
description:
- Optional string that can be used in the HTTPADV check as an alternative to the data object.
- Postdata should be a single string to post.
type: str
data:
description:
- Optional objects used by HTTPADV ('data') can also be used for CLUSTER.
- They are formatted as key:value pairs.
type: dict
websocketdata:
description:
- Data that will be sent to the websocket
type: str
database:
description:
- name of database
type: str
edns:
description:
- used to send EDNS(0) OPT pseudo-records in a DNS query in the DOHDOT check type
type: dict
receiveheaders:
description:
- Optional objects used by HTTPADV ('data' can also be used for CLUSTER.
- They are formatted as key:value pairs.
type: dict
sendheaders:
description:
- Optional objects used by HTTPADV ('data' can also be used for CLUSTER.
- They are formatted as key:value pairs.
type: dict
method:
description:
- optional string used by the HTTPADV check to specify the HTTP method.
type: str
choices: [GET, POST, PUT, HEAD, TRACE, CONNECT]
statuscode:
description:
- Optional integer specifying the expected status code in the response to an HTTPADV check.
type: int
ipv6:
description:
- Specify if the check should run against an ipv6 address.
- PING, HTTP, HTTPCONTENT, HTTPADV, WHOIS checks.
type: bool
redistype:
description:
- Values: standalone, sentinel, or cluster
type: str
regex:
description:
- treat 'contentstring' as a regular expression if true
type: bool
sentinelname:
description:
- required if redistype is "sentinel"
- Set to the "master name" that is in your sentinel configuration
type: str
servername:
description:
- FQDN sent to SNI services in the SSL check
type: str
snmpv:
description:
- String specifying the SNMP version the check should use.
type: str
default: 1
choices: [1, 2c]
snmpcom:
description:
- String specifying the SNMP community indicator that should be used.
type: str
default: public
verifyvolume:
description:
- Enable the volume detection feature - AUDIO check only.
type: bool
volumemin:
description:
- acceptable range -90 to 0, used by the volume detection feature - AUDIO check only.
type: int
whoisserver:
description:
- Specify the WHOIS server FQDN or IPv(4/6) to query - WHOIS check only.
type: str
notifications:
description:
- A single contact/contact group made with a list of dictionaries
notifydelay:
description:
- If there should be any delay in minutes for notifications
default: 0
type: int
notifyschedule:
description:
- The schedule you want to use for notifications
default: All the time
type: str
author:
- NodePing (@nodeping)
"""
EXAMPLES = """
---
- hosts: localhost
vars:
nodeping_api_token: your-token-here
tasks:
# Create a ping check to check every minute with single contact
- name: Create a ping check with 3 minute notification delay
nodeping:
action: create
checktype: PING
label: ping_my_host
target: example.com
interval: 1
enabled: yes
runlocations: nam
notifications:
- name: My Email
address: [email protected]
notifydelay: 3
notifyschedule: All the time
- group: My Group
notifydelay: 0
notifyschedule: Nights
- contact: BKPGH
notifydelay: 0
notifyschedule: Days
- group: 201205050153W2Q4C-G-3QJWG
notifydelay: 15
notifyschedule: All the time
- notificationprofile: 201205050153W2Q4C-P-3JKXH
# Create a DNS check with a contact group for notifications with Daytime alerts
- name: Create DNS check to check every 5 minutes
nodeping:
action: create
checktype: DNS
label: dns_query
target: ns1.example.com
interval: 5
dnstype: A
dnstoresolve: example.com
contentstring: 123.231.100.5
notifications:
- group: mygroup
notifydelay: 0
notifyschedule: Daytime
- notificationprofile: My Awesome Profile
# Modify a check based on its checkid
- name: Modify an existing check to ping IPv6
nodeping:
action: update
checkid: 201205050153W2Q4C-0J2HSIRF
ipv6: yes
# Delete a check
- name: Delete this check based on its ID
nodeping:
action: delete
checkid: 201205050153W2Q4C-0J2HSIRF
"""
RETURN = """
original_message:
description: The original name param that was passed in
type: str
returned: always
message:
description: The response that NodePing returns after a check is created/updated/deleted
type: dict
returned: always
"""
NODEPING_IMPORT_ERROR = None
try:
import nodepingpy
except ImportError:
NODEPING_IMPORT_ERROR = traceback.format_exc()
IMPORTED_NODEPING_API = False
else:
IMPORTED_NODEPING_API = True
def get_nodeping_check(parameters):
"""Get the user defined check by its checkid."""
token = parameters["token"]
customerid = parameters["customerid"]
checkid = parameters["checkid"]
if checkid and checkid.lower() == "all":
result = nodepingpy.checks.get_all(token, customerid)
elif checkid:
result = nodepingpy.checks.get_by_id(token, checkid, customerid)
elif parameters["label"] and not checkid:
get_checks = nodepingpy.checks.get_all(token, customerid)
for _, value in get_checks.items():
if value["label"] == parameters["label"]:
result = value
break
else:
result = {"error": "Check ID label not found"}
else:
result = nodepingpy.checks.get_all(token, customerid)
try:
result.update({"changed": True})
except KeyError:
result.update({"changed": False})
return (False, checkid, result)
else:
return (True, checkid, result)
def create_nodeping_check(parameters):
"""Create a NodePing check."""
token = parameters["token"]
customerid = parameters["customerid"]
name = parameters["label"] or parameters["target"]
checktype = parameters["checktype"].upper()
classname = "{}Check".format(checktype)
(_, checkclass) = [
func
for func in inspect.getmembers(nodepingpy.checktypes)
if inspect.isclass(func[1]) and func[0].upper() == classname.upper()
][0]
# websocketdata isn't part of the API but is necessary to get the data in
# string format for the 'data' key. This is a workaround to ensure the
# NodePing API gets the expected data key, and make sure the Ansible
# module is happy with the other `data` keys that are a dict.
if checktype == "WEBSOCKET":
parameters.update({"data": parameters["websocketdata"]})
del parameters["websocketdata"]
if parameters["mute"]:
parameters.update({"mute": set_mute_timestamp(parameters["mute"])})
# Get contacts & notification schedules if they exist
if parameters["notifications"]:
notifications = parameters["notifications"]
if not isinstance(notifications, list):
notifications = [notifications]
parameters.update(
{"notifications": convert_contacts(notifications, token, customerid)}
)
args_dict = {}
check_keys = checkclass.__annotations__.keys()
for key in parameters.keys():
if key in check_keys:
args_dict.update({key: parameters[key]})
result = nodepingpy.checks.create_check(token, checkclass(**args_dict), customerid)
try:
created = bool(result["created"])
result.update({"changed": True})
except KeyError:
result.update({"changed": False})
return (False, name, result)
else:
return (created, name, result)
def update_nodeping_check(parameters):
"""Update an existing NodePing check."""
token = parameters["token"]
label = parameters["label"]
customerid = parameters["customerid"]
check_id = parameters["checkid"]
oldresult = nodepingpy.checks.get_by_id(token, check_id, customerid)
checktype = oldresult["type"]
# Sometimes dep is an empty string, set it to False since updating it
# may set the value to False
if "dep" in oldresult.keys() and oldresult["dep"] == "":
oldresult["dep"] = False
classname = "{}Check".format(checktype)
(_, checkclass) = [
func
for func in inspect.getmembers(nodepingpy.checktypes)
if inspect.isclass(func[1]) and func[0].upper() == classname.upper()
][0]
# websocketdata isn't part of the API but is necessary to get the data in
# string format for the 'data' key. This is a workaround to ensure the
# NodePing API gets the expected data key, and make sure the Ansible
# module is happy with the other `data` keys that are a dict.
if checktype == "WEBSOCKET":
parameters.update({"data": parameters["websocketdata"]})
del parameters["websocketdata"]
if parameters["mute"]:
parameters.update({"mute": set_mute_timestamp(parameters["mute"])})
# Get contacts & notification schedules if they exist
if parameters["notifications"]:
notifications = parameters["notifications"]
if not isinstance(notifications, list):
notifications = [notifications]
parameters.update(
{"notifications": convert_contacts(notifications, token, customerid)}
)
args_dict = {}
check_keys = checkclass.__annotations__.keys()
for key in parameters.keys():
if key in check_keys and parameters[key] is not None:
args_dict.update({key: parameters[key]})
updated = nodepingpy.checks.update_check(token, check_id, checktype, args_dict, customerid)
newresult = nodepingpy.checks.get_by_id(token, check_id, customerid)
# Strip out the modified fields before checking. NodePing recognizes a check
# as changed by simply doing a PUT request for the checkid. We want to check
# changes by any of the fields we submitted
del oldresult["modified"]
del newresult["modified"]
try:
updated["modified"]
except KeyError:
return(False, check_id, updated)
else:
for k, v in oldresult.items():
if v != newresult[k]:
updated["changed"] = True
return (True, "{} changed".format(label), updated)
updated["changed"] = False
return(True, check_id, updated)
def delete_nodeping_check(parameters):
"""Delete an existing NodePing check."""
token = parameters["token"]
checkid = parameters["checkid"]
customerid = parameters["customerid"]
result = nodepingpy.checks.delete_check(token, checkid, customerid)
try:
result["error"]
except KeyError:
result["changed"] = True
return (True, checkid, result)
else:
result["changed"] = False
return (False, checkid, result)
def convert_contacts(notification_contacts, token, customerid):
"""Take in a contact/group list and converts to the expected IDs"""
# notification_contacts [{'contact': 'RCMXLQR8', 'notifydelay': 0, 'notifyschedule': 'All the time'}]
all_contacts = []
account_contacts = account_groups = account_notificationprofiles = {}
for contact in notification_contacts:
if "name" in contact.keys():
if not account_contacts:
account_contacts = nodepingpy.contacts.get_all(token, customerid)
for _, value in account_contacts.items():
if contact["name"] == value["name"]:
for key, address in value["addresses"].items():
if address["address"] == contact["address"]:
all_contacts += [
{
key: {
"schedule": contact["notifyschedule"],
"delay": contact["notifydelay"],
}
}
]
elif "group" in contact.keys():
if not account_groups:
account_groups = nodepingpy.contactgroups.get_all(token, customerid)
for key, value in account_groups.items():
if value["name"] == contact["group"] or key == contact["group"]:
all_contacts += [
{
key: {
"schedule": contact["notifyschedule"],
"delay": contact["notifydelay"],
}
}
]
elif "notificationprofile" in contact.keys():
if not account_notificationprofiles:
account_notificationprofiles = nodepingpy.notificationprofiles.get_all(
token, customerid
)
for key, value in account_notificationprofiles.items():
if (
value["name"] == contact["notificationprofile"]
or key == contact["notificationprofile"]
):
all_contacts += [{key: {"schedule": "All", "delay": 0}}]
elif "contact" in contact.keys():
all_contacts += [
{
contact["contact"]: {
"schedule": contact["notifyschedule"],
"delay": contact["notifydelay"],
}
}
]
else:
continue
return all_contacts
def set_mute_timestamp(mute):
"""Convert Mute time to timestamp"""
if isinstance(mute, int):
return mute
else:
if mute.upper().endswith("D"):
return int(time() * 1000) + (int(mute[:-1]) * 86400000)
elif mute.upper().endswith("H"):
return int(time() * 1000) + (int(mute[:-1]) * 3600000)
elif mute.upper().endswith("M"):
return int(time() * 1000) + (int(mute[:-1]) * 60000)
elif mute.upper().endswith("S"):
return int(time() * 1000) + int(mute[:-1])
elif mute.upper() == "TRUE" or mute.upper() == "YES":
return True
elif mute.upper() == "FALSE" or mute.upper() == "NO":
return False
else:
return False
def run_module():
# define available arguments/parameters a user can pass to the module
module_args = dict(
token=dict(type="str", required=True, no_log=True),
customerid=dict(type="str", required=False),
checktype=dict(type="str", required=False),
checkid=dict(type="str", required=False),
label=dict(type="str", required=False),
target=dict(type="str", required=False),
action=dict(
type="str", required=True, choices=["get", "create", "update", "delete"]
),
interval=dict(type="int", required=False),
enabled=dict(type="bool", required=False),
public=dict(type="bool", required=False),
runlocations=dict(type="str", required=False),
homeloc=dict(type="str", required=False),
threshold=dict(type="int", required=False),
sens=dict(type="int", required=False),
dep=dict(type="str", required=False),
mute=dict(type="str", required=False, default="off"),
description=dict(type="str", required=False),
checktoken=dict(type="str", required=False),
clientcert=dict(type="str", required=False),
contentstring=dict(type="str", required=False),
dohdot=dict(type="str", required=False),
dnssection=dict(type="str", required=False),
dnstype=dict(type="str", required=False),
dnstoresolve=dict(type="str", required=False),
dnsrd=dict(type="bool", required=False),
transport=dict(type="str", required=False, choices=["udp", "tcp"]),
follow=dict(type="bool", required=False),
email=dict(type="str", required=False),
port=dict(type="int", required=False),
username=dict(type="str", required=False),
password=dict(type="str", required=False, no_log=True),
query=dict(type="str", required=False),
secure=dict(type="bool", required=False),
sshkey=dict(type="str", required=False),
verify=dict(type="bool", required=False),
hosts=dict(type="dict", required=False),
ignore=dict(type="str", required=False),
invert=dict(type="bool", required=False),
warningdays=dict(type="int", required=False),
fields=dict(type="dict", required=False),
postdata=dict(type="str", required=False),
data=dict(type="dict", required=False),
websocketdata=dict(type="str", required=False),
receiveheaders=dict(type="dict", required=False),
sendheaders=dict(type="dict", required=False),
database=dict(type="str", required=False),
edns=dict(type="dict", required=False),
method=dict(
type="str",
required=False,
choices=["GET", "POST", "PUT", "HEAD", "TRACE", "CONNECT"],
),
statuscode=dict(type="int", required=False),
ipv6=dict(type="bool", required=False),
redistype=dict(type="str", required=False),
regex=dict(type="str", required=False),
sentinelname=dict(type="str", required=False),
servername=dict(type="str", required=False),
snmpv=dict(type="str", required=False, choices=["1", "2c"]),
snmpcom=dict(type="str", required=False),
verifyvolume=dict(type="bool", required=False),
volumein=dict(type="int", required=False),
whoisserver=dict(type="str", required=False),
notifications=dict(type="list", required=False),
notifydelay=dict(type="int", required=False),
notifyschedule=dict(type="str", required=False),
)
# seed the result dict in the object
# we primarily care about changed and state
# change is if this module effectively modified the target
# state will include any data that you want your module to pass back
# for consumption, for example, in a subsequent task
result = dict(changed=False, original_message="", message="")
# the AnsibleModule object will be our abstraction working with Ansible
# this includes instantiation, a couple of common attr would be the
# args/params passed to the execution, as well as if the module
# supports check mode
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
if not IMPORTED_NODEPING_API:
module.fail_json(
msg="Missing import lib: nodepingpy", exception=NODEPING_IMPORT_ERROR
)
# if the user is working with this module in only check mode we do not
# want to make any changes to the environment, just return the current
# state with no modifications
if module.check_mode:
module.exit_json(**result)
params = module.params
action = params["action"]
if action == "get":
status, label, output = get_nodeping_check(params)
if not status:
module.fail_json(
msg="Failed to get checkid %s" % params["checkid"], **output
)
elif action == "create":
checktype = params["checktype"]
# If user specified to create a check, but not the type
# a check cannot be made
if not checktype:
module.fail_json(msg="No Check Type specified for check creation")
status, label, output = create_nodeping_check(params)
if not status:
module.fail_json(msg="Failed to create %s" % label, **output)
elif action == "update":
if not params["checkid"]:
module.fail_json(msg="No checkid specified for updating check")
status, label, output = update_nodeping_check(params)
if not status:
module.fail_json(msg="Failed to update %s" % label, **output)
elif action == "delete":
if not params["checkid"]:
module.fail_json(msg="No checkid provided to delete a check")
status, label, output = delete_nodeping_check(params)
if not status:
module.fail_json(
msg="Failed to delete checkid %s" % params["checkid"], **output
)
# manipulate or modify the state as needed (this is going to be the
# part where your module will do what it needs to do)
result["original_message"] = ""
result["message"] = output
# use whatever logic you need to determine whether or not this module
# made any modifications to your target
try:
output["changed"]
except KeyError:
result["changed"] = False
else:
result["changed"] = output.pop("changed")
# during the execution of the module, if there is an exception or a
# conditional state that effectively causes a failure, run
# AnsibleModule.fail_json() to pass in the message and the result
# if result['changed'] == False:
# module.fail_json(msg='You requested this to fail', **result)
# in the event of a successful module execution, you will want to
# simple AnsibleModule.exit_json(), passing the key/value results
module.exit_json(**result)
def main():
run_module()
if __name__ == "__main__":
main()