Add custom modules
authorLorin Hochstein <lorin.hochstein@sendgrid.com>
Sun, 8 Feb 2015 02:07:51 +0000 (21:07 -0500)
committerLorin Hochstein <lorin.hochstein@sendgrid.com>
Sun, 8 Feb 2015 02:07:51 +0000 (21:07 -0500)
ch10/playbooks/library/can_reach [new file with mode: 0644]
ch10/playbooks/library/can_reach_bash [new file with mode: 0644]
ch10/playbooks/scripts/can_reach.sh [moved from ch10/playbooks/files/can_reach.sh with 100% similarity]

diff --git a/ch10/playbooks/library/can_reach b/ch10/playbooks/library/can_reach
new file mode 100644 (file)
index 0000000..fbfe520
--- /dev/null
@@ -0,0 +1,37 @@
+#!/usr/bin/python
+
+def can_reach(module, host, port, timeout):
+    nc_path = module.get_bin_path('nc', required=True) 1
+    args = [nc_path, "-z", "-w", str(timeout),
+            host, str(port)]
+    (rc, stdout, stderr) = module.run_command(args) 2
+    return rc == 0
+
+def main():
+    module = AnsibleModule( 3
+        argument_spec=dict( 4
+            host=dict(required=True), 5
+            port=dict(required=True, type='int'),
+            timeout=dict(required=False, type='int', default=3) 6
+        ),
+        supports_check_mode=True 7
+    )
+
+    # In check mode, we take no action
+    # Since this module never changes system state, we just
+    # return changed=False
+    if module.check_mode: 8
+        module.exit_json(changed=False) 9
+
+    host = module.params['host'] 10
+    port = module.params['port']
+    timeout = module.params['timeout']
+
+    if can_reach(module, host, port, timeout):
+        module.exit_json(changed=False)
+    else:
+        msg = "Could not reach %s:%s" % (host, port)
+        module.fail_json(msg=msg) 11
+
+from ansible.module_utils.basic import * 12
+main()
diff --git a/ch10/playbooks/library/can_reach_bash b/ch10/playbooks/library/can_reach_bash
new file mode 100644 (file)
index 0000000..c95a07c
--- /dev/null
@@ -0,0 +1,17 @@
+#!/bin/bash
+# WANT_JSON
+
+# Read the variables form the file
+host=`jq -r .host < $1`
+port=`jq -r .port < $1`
+timeout=`jq -r .timeout < $1`
+
+# Check if we can reach the host
+nc -z -w $timeout $host $port
+
+# Output based on success or failure
+if [ $? -eq 0 ]; then
+    echo '{"changed": false}'
+else
+    echo "{\"failed\": true, \"msg\": \"could not reach $host:$port\"}"
+fi