From dfe4b16fca6ace1a7b2f2e158cdb2aae2e27ca71 Mon Sep 17 00:00:00 2001 From: Lorin Hochstein Date: Sat, 7 Feb 2015 21:07:51 -0500 Subject: [PATCH] Add custom modules --- ch10/playbooks/library/can_reach | 37 +++++++++++++++++++ ch10/playbooks/library/can_reach_bash | 17 +++++++++ .../playbooks/{files => scripts}/can_reach.sh | 0 3 files changed, 54 insertions(+) create mode 100644 ch10/playbooks/library/can_reach create mode 100644 ch10/playbooks/library/can_reach_bash rename ch10/playbooks/{files => scripts}/can_reach.sh (100%) diff --git a/ch10/playbooks/library/can_reach b/ch10/playbooks/library/can_reach new file mode 100644 index 0000000..fbfe520 --- /dev/null +++ b/ch10/playbooks/library/can_reach @@ -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 index 0000000..c95a07c --- /dev/null +++ b/ch10/playbooks/library/can_reach_bash @@ -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 diff --git a/ch10/playbooks/files/can_reach.sh b/ch10/playbooks/scripts/can_reach.sh similarity index 100% rename from ch10/playbooks/files/can_reach.sh rename to ch10/playbooks/scripts/can_reach.sh -- 2.44.0