From a453ac31f3428614cceb99027f8efbdb9258a40b Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Tue, 14 May 2024 22:03:01 +0200 Subject: Adding upstream version 2.10.7+merged+base+2.10.8+dfsg. Signed-off-by: Daniel Baumann --- .../wti/remote/plugins/lookup/cpm_metering.py | 174 ++++++ .../wti/remote/plugins/lookup/cpm_status.py | 164 ++++++ .../wti/remote/plugins/modules/cpm_alarm_info.py | 179 ++++++ .../remote/plugins/modules/cpm_config_backup.py | 204 +++++++ .../remote/plugins/modules/cpm_config_restore.py | 208 +++++++ .../wti/remote/plugins/modules/cpm_current_info.py | 241 ++++++++ .../remote/plugins/modules/cpm_firmware_info.py | 187 +++++++ .../remote/plugins/modules/cpm_interface_config.py | 509 +++++++++++++++++ .../remote/plugins/modules/cpm_interface_info.py | 195 +++++++ .../remote/plugins/modules/cpm_iptables_config.py | 295 ++++++++++ .../remote/plugins/modules/cpm_iptables_info.py | 175 ++++++ .../wti/remote/plugins/modules/cpm_plugconfig.py | 272 ++++++++++ .../wti/remote/plugins/modules/cpm_plugcontrol.py | 234 ++++++++ .../wti/remote/plugins/modules/cpm_power_info.py | 242 +++++++++ .../plugins/modules/cpm_serial_port_config.py | 360 ++++++++++++ .../remote/plugins/modules/cpm_serial_port_info.py | 221 ++++++++ .../wti/remote/plugins/modules/cpm_snmp_config.py | 603 +++++++++++++++++++++ .../wti/remote/plugins/modules/cpm_snmp_info.py | 193 +++++++ .../wti/remote/plugins/modules/cpm_status_info.py | 307 +++++++++++ .../wti/remote/plugins/modules/cpm_temp_info.py | 187 +++++++ .../wti/remote/plugins/modules/cpm_time_config.py | 410 ++++++++++++++ .../wti/remote/plugins/modules/cpm_time_info.py | 190 +++++++ .../wti/remote/plugins/modules/cpm_user.py | 355 ++++++++++++ 23 files changed, 6105 insertions(+) create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_metering.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_status.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_alarm_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_backup.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_restore.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_current_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_firmware_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_config.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_config.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugconfig.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugcontrol.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_power_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_config.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_config.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_status_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_temp_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_config.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_info.py create mode 100644 collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_user.py (limited to 'collections-debian-merged/ansible_collections/wti/remote/plugins') diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_metering.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_metering.py new file mode 100644 index 00000000..cbf6470c --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_metering.py @@ -0,0 +1,174 @@ +# (c) 2018, Western Telematic Inc. +# (c) 2012-18 Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +lookup: cpm_metering +author: "Western Telematic Inc. (@wtinetworkgear)" +version_added: "2.7" +short_description: Get Power and Current data from WTI OOB/Combo and PDU devices +description: + - "Get Power and Current data from WTI OOB/Combo and PDU devices" +options: + _terms: + description: + - This is the Action to send the module. + type: str + required: true + choices: [ "getpower", "getcurrent" ] + 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 + choices: [ True, False ] + 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 + default: True + startdate: + description: + - Start date of the range to look for power data + type: str + required: false + enddate: + description: + - End date of the range to look for power data + type: str + required: false +""" + +EXAMPLES = """ +# Get Power data + - name: Get Power data for a given WTI device + - debug: + var: lookup('cpm_metering', + 'getpower', + validate_certs=true, + use_https=true, + cpm_url='rest.wti.com', + cpm_username='restpower', + cpm_password='restfulpowerpass12') + +# Get Current data + - name: Get Current data for a given WTI device + - debug: + var: lookup('cpm_metering', + 'getcurrent', + validate_certs=true, + use_https=true, + cpm_url='rest.wti.com', + cpm_username='restpower', + cpm_password='restfulpowerpass12') + +# Get Power data for a date range + - name: Get Power data for a given WTI device given a certain date range + - debug: + var: lookup('cpm_metering', + 'getpower', + validate_certs=true, + use_https=true, + cpm_url='rest.wti.com', + cpm_username='restpower', + cpm_password='restfulpowerpass12', + startdate='08-12-2018' + enddate='08-14-2018') +""" + +RETURN = """ + _list: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +import base64 + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase +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 +from ansible.utils.display import Display + +display = Display() + + +class LookupModule(LookupBase): + + def run(self, terms, variables=None, **kwargs): + self.set_options(direct=kwargs) + + ret = [] + for term in terms: + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(self.get_option('cpm_username'), self.get_option('cpm_password')), + errors='surrogate_or_strict'))) + + additional = "" + if self.get_option("startdate") is not None and (len(self.get_option("startdate")) > 0): + if self.get_option("enddate") is not None and (len(self.get_option("enddate")) > 0): + additional = "?startdate=" + self.get_option("startdate") + "&enddate=" + self.get_option("enddate") + + if self.get_option('use_https') is True: + protocol = "https://" + else: + protocol = "http://" + + if (term == 'getpower'): + fullurl = ("%s%s/api/v2/config/power" % (protocol, self.get_option('cpm_url'))) + elif (term == 'getcurrent'): + fullurl = ("%s%s/api/v2/config/current" % (protocol, self.get_option('cpm_url'))) + else: + raise AnsibleError("Power command not recognized %s " % (term)) + + if (len(additional) > 0): + fullurl += additional + + display.vvvv("cpm_metering connecting to %s" % fullurl) + + try: + response = open_url(fullurl, validate_certs=self.get_option('validate_certs'), use_proxy=self.get_option('use_proxy'), + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + except HTTPError as e: + raise AnsibleError("Received HTTP error for %s : %s" % (fullurl, to_native(e))) + except URLError as e: + raise AnsibleError("Failed lookup url for %s : %s" % (fullurl, to_native(e))) + except SSLValidationError as e: + raise AnsibleError("Error validating the server's certificate for %s: %s" % (fullurl, to_native(e))) + except ConnectionError as e: + raise AnsibleError("Error connecting to %s: %s" % (fullurl, to_native(e))) + + ret.append(to_text(response.read())) + + return ret diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_status.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_status.py new file mode 100644 index 00000000..37b67c67 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/lookup/cpm_status.py @@ -0,0 +1,164 @@ +# (c) 2018, Western Telematic Inc. +# (c) 2012-18 Ansible Project +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +lookup: cpm_status +author: "Western Telematic Inc. (@wtinetworkgear)" +version_added: "2.7" +short_description: Get status and parameters from WTI OOB and PDU devices. +description: + - "Get various status and parameters from WTI OOB and PDU devices." +options: + _terms: + description: + - This is the Action to send the module. + type: str + required: true + choices: [ "temperature", "firmware", "status", "alarms" ] + 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 Basic Authentication Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Basic Authentication 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: boolean + default: True +""" + +EXAMPLES = """ +# Get temperature + - name: run Get Device Temperature + - debug: + var: lookup('cpm_status', + 'temperature', + validate_certs=true, + use_https=true, + cpm_url='rest.wti.com', + cpm_username='rest', + cpm_password='restfulpassword') + +# Get firmware version + - name: Get the firmware version of a given WTI device + - debug: + var: lookup('cpm_status', + 'firmware', + validate_certs=false, + use_https=true, + cpm_url="192.168.0.158", + cpm_username="super", + cpm_password="super") + +# Get status output + - name: Get the status output from a given WTI device + - debug: + var: lookup('cpm_status', + 'status', + validate_certs=true, + use_https=true, + cpm_url="rest.wti.com", + cpm_username="rest", + cpm_password="restfulpassword") + +# Get Alarm output + - name: Get the alarms status of a given WTI device + - debug: + var: lookup('cpm_status', + 'alarms', + validate_certs=false, + use_https=false, + cpm_url="192.168.0.158", + cpm_username="super", + cpm_password="super") +""" + +RETURN = """ + _list: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +import base64 + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase +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 + + +class LookupModule(LookupBase): + + def run(self, terms, variables=None, **kwargs): + self.set_options(direct=kwargs) + + ret = [] + + for term in terms: + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(self.get_option('cpm_username'), self.get_option('cpm_password')), + errors='surrogate_or_strict'))) + + if self.get_option('use_https') is True: + protocol = "https://" + else: + protocol = "http://" + + if (term == 'temperature'): + fullurl = ("%s%s/api/v2/status/temperature" % (protocol, self.get_option('cpm_url'))) + elif (term == 'firmware'): + fullurl = ("%s%s/api/v2/status/firmware" % (protocol, self.get_option('cpm_url'))) + elif (term == 'status'): + fullurl = ("%s%s/api/v2/status/status" % (protocol, self.get_option('cpm_url'))) + elif (term == 'alarms'): + fullurl = ("%s%s/api/v2/status/alarms" % (protocol, self.get_option('cpm_url'))) + else: + raise AnsibleError("Status command not recognized %s " % (term)) + + try: + response = open_url(fullurl, validate_certs=self.get_option('validate_certs'), use_proxy=self.get_option('use_proxy'), + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + except HTTPError as e: + raise AnsibleError("Received HTTP error for %s : %s" % (fullurl, to_native(e))) + except URLError as e: + raise AnsibleError("Failed lookup url for %s : %s" % (fullurl, to_native(e))) + except SSLValidationError as e: + raise AnsibleError("Error validating the server's certificate for %s: %s" % (fullurl, to_native(e))) + except ConnectionError as e: + raise AnsibleError("Error connecting to %s: %s" % (fullurl, to_native(e))) + + ret.append(to_text(response.read())) + + return ret diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_alarm_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_alarm_info.py new file mode 100644 index 00000000..a1f18e1a --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_alarm_info.py @@ -0,0 +1,179 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI alarm information 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_alarm_info +version_added: "2.9" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get alarm information from WTI OOB and PDU devices +description: + - "Get temperature alarm from 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Alarm Information for a WTI device + cpm_alarm_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Alarm Information for a WTI device + cpm_alarm_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + alarms: + description: Current alarm status of the WTI device after module execution. + returned: success + type: dict + sample: [ {"name": "OVER CURRENT (INITIAL)","status": "0"}, + {"name": "OVER CURRENT (CRITICAL)","status": "0"}, + {"name": "OVER TEMPERATURE (INITIAL)","status": "0"} ] + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +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 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), + 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/status/alarms" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_backup.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_backup.py new file mode 100644 index 00000000..c206d69d --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_backup.py @@ -0,0 +1,204 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 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 retrieve WTI 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_config_backup +version_added: "2.9" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get parameters from WTI OOB and PDU devices +description: + - "Get parameters from WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to get the parameters from. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to get the parameters from. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to get the parameters from. + type: str + required: true + cpm_path: + description: + - This is the directory path to store the WTI device configuration file. + type: str + required: false + default: "/tmp/" + 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Parameters for a WTI device + cpm_config_backup: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false +""" + +RETURN = """ +data: + description: The XML configuration of the WTI device queried + returned: always + type: complex + contains: + status: + description: List of status returns from backup operation + returned: success + type: list + sample: + - code: 0 + savedfilename: "/tmp/wti-192-10-10-239-2020-02-13T16-05-57.xml" + text: "ok" +""" + +import base64 +import json +import datetime + +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 get_unit_type(filedata): + beginsearch = filedata.find("unit_type_info=\"") + beginsearch = (beginsearch + 16) + endsearch = filedata.find("\">", beginsearch) + if (((endsearch == -1) | (beginsearch == -1)) | (endsearch < beginsearch) | ((endsearch - beginsearch) > 16)): + header = "wti" + else: + header = filedata[beginsearch:beginsearch + (endsearch - beginsearch)] + return (header) + + +def normalize_string(filedata): + filedata = filedata.replace(":", "-") + filedata = filedata.replace(".", "-") + return (filedata) + + +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), + cpm_path=dict(type='str', default="/tmp/"), + 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/cgi-bin/gethtml?formWTIDownloadConfigXML.html" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/xml', '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) + + json_string = response.read() + + try: + f = open(normalize_string(to_native(module.params['cpm_path'])) + get_unit_type(to_native(json_string)) + "-" + to_native(module.params['cpm_url']) + + "-" + datetime.datetime.now().replace(microsecond=0).isoformat() + ".xml", "wb") + f.write(json_string) + f.close() + json_string = '{\"status\": { \"code\": \"0\", \"text\": \"ok\", \"savedfilename\": \"%s%s-%s-%s.xml\" }}' \ + % (normalize_string(to_native(module.params['cpm_path'])), get_unit_type(to_native(json_string)), + to_native(module.params['cpm_url']), datetime.datetime.now().replace(microsecond=0).isoformat()) + + except Exception as e: + json_string = "{\"status\": { \"code\": \"1\", \"text\": \"error: " + str(e) + "\", \"savedfilename\": \"\" }}" + + result['data'] = json_string + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_restore.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_restore.py new file mode 100644 index 00000000..7b028da6 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_config_restore.py @@ -0,0 +1,208 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 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 retrieve WTI 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_config_restore +version_added: "2.9" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get parameters from WTI OOB and PDU devices +description: + - "Get parameters from WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to get the parameters from. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to get the parameters from. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to get the parameters from. + type: str + required: true + cpm_path: + description: + - This is the directory path to the existing the WTI device configuration file. + type: str + required: false + default: "/tmp/" + cpm_filename: + description: + - This is the filename of the existing WTI device configuration file. + 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Parameters for a WTI device + cpm_config_restore: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + cpm_path: "/tmp/" + cpm_filename: "wti-192-10-10-239-2020-02-13T16-05-57-xml" + use_https: true + validate_certs: false +""" + +RETURN = """ +data: + description: The output XML configuration of the WTI device queried + returned: always + type: complex + contains: + filelength: + description: Length of the file uploaded in bytes + returned: success + type: int + sample: + - filelength: 329439 + status: + description: List of status returns from backup operation + returned: success + type: list + sample: + - code: 0 + text: "ok" + unittimestamp: "2020-02-14T00:18:57+00:00" +""" + +import base64 +import json +import datetime + +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 get_unit_type(filedata): + beginsearch = filedata.find("unit_type_info=\"") + beginsearch = (beginsearch + 16) + endsearch = filedata.find("\">", beginsearch) + if (((endsearch == -1) | (beginsearch == -1)) | (endsearch < beginsearch) | ((endsearch - beginsearch) > 16)): + header = "wti" + else: + header = filedata[beginsearch:beginsearch + (endsearch - beginsearch)] + return (header) + + +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), + cpm_path=dict(type='str', default="/tmp/"), + cpm_filename=dict(type='str', required=True), + 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) + + try: + f = open(to_native(module.params['cpm_path']) + to_native(module.params['cpm_filename']), "rb") + cszData = f.read() + f.close() + except Exception as e: + json_string = "{\"status\": { \"code\": \"1\", \"text\": \"error: " + str(e) + "\" }}" + result['data'] = json_string + module.exit_json(**result) + + 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/cgi-bin/getfile" % (protocol, to_native(module.params['cpm_url']))) + + try: + xmlfile = open(to_native(module.params['cpm_path']) + to_native(module.params['cpm_filename']), 'rb') + xmlfile.close() + response = open_url(fullurl, data=cszData, method='POST', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/xml', '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() + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_current_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_current_info.py new file mode 100644 index 00000000..a068cd0b --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_current_info.py @@ -0,0 +1,241 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI Current information 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_current_info +version_added: "2.9" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get the Current Information of a WTI device +description: + - "Get the Current Information of a WTI device" +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 + cpm_startdate: + description: + - Start date of the range to look for current data + type: str + required: false + cpm_enddate: + description: + - End date of the range to look for current data + type: str + required: false + 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Current Information of a WTI device + cpm_current_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Current Information of a WTI device + cpm_current_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false + startdate: 01-12-2020" + enddate: 02-16-2020" +""" + +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: "2020-02-24T20:54:03+00:00" + powerunit: + description: Identifies if the WTI device is a power type device. + returned: success + type: str + sample: "1" + outletmetering: + description: Identifies if the WTI device has Poiwer Outlet metering. + returned: success + type: str + sample: "1" + ats: + description: Identifies if the WTI device is an ATS type of power device. + returned: success + type: str + sample: "1" + plugcount: + description: Current outlet plug count of the WTI device after module execution. + returned: success + type: str + sample: "8" + powerfactor: + description: Power factor of the WTI device after module execution. + returned: success + type: str + sample: "100" + powereff: + description: Power efficiency of the WTI device after module execution. + returned: success + type: str + sample: "100" + powerdatacount: + description: Total powerdata samples returned after module execution. + returned: success + type: str + sample: "1" + powerdata: + description: Power data of the WTI device after module execution. + returned: success + type: dict + sample: [ { "timestamp": "2020-02-24T23:29:31+00:00","temperature": "90","format": "F", + "branch1": [{ "voltage1": "118.00","current1": "0.00"}] }] + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +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 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), + cpm_startdate=dict(type='str', required=False), + cpm_enddate=dict(type='str', required=False), + 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://" + + additional = "" + + if module.params['cpm_startdate'] is not None and (len(to_native(module.params['cpm_startdate'])) > 0): + if module.params['cpm_enddate'] is not None and (len(to_native(module.params['cpm_enddate'])) > 0): + additional = "?startdate=%s&enddate=%s" % (to_native(module.params['cpm_startdate']), to_native(module.params['cpm_enddate'])) + + fullurl = ("%s%s/api/v2/status/current" % (protocol, to_native(module.params['cpm_url']))) + + if (len(additional) > 0): + fullurl += additional + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_firmware_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_firmware_info.py new file mode 100644 index 00000000..0f53affe --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_firmware_info.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI firmware information 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_firmware_info +version_added: "2.9" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get firmware information from WTI OOB and PDU devices +description: + - "Get firmware information from 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Firmware Information for a WTI device + cpm_firmware_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Firmware Information for a WTI device + cpm_firmware_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + firmware: + description: Current Firmware version of the WTI device. + returned: success + type: str + sample: "6.60" + family: + description: Current family type (Console = 1 or Power = 0) of the WTI device. + returned: success + type: str + sample: "1" + fips: + description: If WTI device is a no FIPS only device. + returned: success + type: str + sample: "2020-02-24T20:54:03+00:00" + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +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 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), + 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/status/firmware" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_config.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_config.py new file mode 100644 index 00000000..8b86664d --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_config.py @@ -0,0 +1,509 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 network interface Parameters on 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_interface_config +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Set network interface parameters in WTI OOB and PDU devices +description: + - "Set network interface 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 + interface: + description: + - This is the ethernet port name that is getting configured. + type: str + required: false + choices: [ "eth0", "eth1" ] + negotiation: + description: + - This is the speed of the interface port being configured. + - 0=Auto, 1=10/half, 2=10/full, 3=100/half, 4=100/full, 5=1000/half, 6=1000/full + type: int + required: false + choices: [ 0, 1, 2, 3, 4, 5, 6 ] + ipv4address: + description: + - IPv4 format IP address for the defined interface Port. + type: str + required: false + ipv4netmask: + description: + - IPv4 format Netmask for the defined interface Port. + type: str + required: false + ipv4gateway: + description: + - IPv4 format Gateway address for the defined interface Port. + type: str + required: false + ipv4dhcpenable: + description: + - Enable IPv4 DHCP request call to obtain confufuration information. + type: int + required: false + choices: [ 0, 1 ] + ipv4dhcphostname: + description: + - Define IPv4 DHCP Hostname. + type: str + required: false + ipv4dhcplease: + description: + - IPv4 DHCP Lease Time. + type: int + required: false + ipv4dhcpobdns: + description: + - IPv6 DHCP Obtain DNS addresses auto. + type: int + required: false + choices: [ 0, 1 ] + ipv4dhcpupdns: + description: + - IPv4 DHCP DNS Server Update. + type: int + required: false + choices: [ 0, 1 ] + ipv4dhcpdefgateway: + description: + - Enable or Disable this ports configuration as the default IPv4 route for the device. + type: int + required: false + choices: [ 0, 1 ] + ipv6address: + description: + - IPv6 format IP address for the defined interface Port. + type: str + required: false + ipv6subnetprefix: + description: + - IPv6 format Subnet Prefix for the defined interface Port. + type: str + required: false + ipv6gateway: + description: + - IPv6 format Gateway address for the defined interface Port. + type: str + required: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Set Network Interface Parameters +- name: Set the Interface Parameters for port eth1 of a WTI device + cpm_interface_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + interface: "eth1" + ipv4address: "192.168.0.14" + ipv4netmask: "255.255.255.0" + ipv4gateway: "192.168.0.1" + negotiation: 0 + +# Set Network Interface Parameters +- name: Set the Interface Parameters for port eth1 to DHCP of a WTI device + cpm_interface_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + interface: "eth1" + negotiation: 0 + ipv4dhcpenable: 1 + ipv4dhcphostname: "" + ipv4dhcplease: -1 + ipv4dhcpobdns: 0 + ipv4dhcpupdns: 0 + ipv4dhcpdefgateway: 0 +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + totalports: + description: Total interface ports requested of the WTI device. + returned: success + type: int + sample: 1 + interface: + description: Current k/v pairs of interface info for the WTI device after module execution. + returned: always + type: dict + sample: {"name": "eth1", "type": "0", "mac_address": "00-09-9b-02-45-db", "is_up": "0", "is_gig": "1", "speed": "10", "negotiation": "0", + "ietf-ipv4": {"address": [{"ip": "10.10.10.2","netmask": "255.255.255.0","gateway": ""}], + "dhcpclient": [{"enable": 0, "hostname": "", "lease": -1, "obdns": 1, "updns": 1}]}, + "ietf-ipv6": {"address": [{"ip": "", "netmask": "", "gateway": "" }]}} +""" + +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_interface): + total_change = protocol = 0 + json_load = ietfstring = negotiation = None + + address = [] + netmask = [] + gateway = [] + dhcphostname = [] + dhcpenable = [] + dhcplease = [] + dhcpobdns = [] + dhcpupdns = [] + dhcpdefgateway = [] + + for x in range(0, 2): + address.insert(x, None) + netmask.insert(x, None) + gateway.insert(x, None) + dhcpenable.insert(x, None) + dhcphostname.insert(x, None) + dhcplease.insert(x, None) + dhcpobdns.insert(x, None) + dhcpupdns.insert(x, None) + dhcpdefgateway.insert(x, None) + + if existing_interface["totalports"] is not None: + if (existing_interface["totalports"] != 1): + return None + + # make sure we are working with the correct ethernet port + if (existing_interface["interface"][0]["name"] != to_native(cpmmodule.params["interface"])): + return None + + if cpmmodule.params["negotiation"] is not None: + if (int(existing_interface["interface"][0]["negotiation"]) != cpmmodule.params["negotiation"]): + total_change = (total_change | 1) + negotiation = to_native(cpmmodule.params["negotiation"]) + + if cpmmodule.params["ipv4address"] is not None: + if (existing_interface["interface"][0]["ietf-ipv4"]["address"][0]["ip"] != cpmmodule.params["ipv4address"]): + total_change = (total_change | 2) + address.insert(protocol, to_native(cpmmodule.params["ipv4address"])) + + if cpmmodule.params["ipv4netmask"] is not None: + if (existing_interface["interface"][0]["ietf-ipv4"]["address"][0]["netmask"] != cpmmodule.params["ipv4netmask"]): + total_change = (total_change | 4) + netmask.insert(protocol, to_native(cpmmodule.params["ipv4netmask"])) + + if cpmmodule.params["ipv4gateway"] is not None: + if (existing_interface["interface"][0]["ietf-ipv4"]["address"][0]["gateway"] != cpmmodule.params["ipv4gateway"]): + total_change = (total_change | 8) + gateway.insert(protocol, to_native(cpmmodule.params["ipv4gateway"])) + + if cpmmodule.params["ipv4dhcpenable"] is not None: + if (int(existing_interface["interface"][0]["ietf-ipv4"]["dhcpclient"][0]["enable"]) != cpmmodule.params["ipv4dhcpenable"]): + total_change = (total_change | 16) + dhcpenable.insert(protocol, to_native(cpmmodule.params["ipv4dhcpenable"])) + + if cpmmodule.params["ipv4dhcphostname"] is not None: + if (existing_interface["interface"][0]["ietf-ipv4"]["dhcpclient"][0]["hostname"] != cpmmodule.params["ipv4dhcphostname"]): + total_change = (total_change | 32) + dhcphostname.insert(protocol, to_native(cpmmodule.params["ipv4dhcphostname"])) + + if cpmmodule.params["ipv4dhcplease"] is not None: + if (int(existing_interface["interface"][0]["ietf-ipv4"]["dhcpclient"][0]["lease"]) != cpmmodule.params["ipv4dhcplease"]): + total_change = (total_change | 64) + dhcplease.insert(protocol, to_native(cpmmodule.params["ipv4dhcplease"])) + + if cpmmodule.params["ipv4dhcpobdns"] is not None: + if (int(existing_interface["interface"][0]["ietf-ipv4"]["dhcpclient"][0]["obdns"]) != cpmmodule.params["ipv4dhcpobdns"]): + total_change = (total_change | 128) + dhcpobdns.insert(protocol, to_native(cpmmodule.params["ipv4dhcpobdns"])) + + if cpmmodule.params["ipv4dhcpupdns"] is not None: + if (int(existing_interface["interface"][0]["ietf-ipv4"]["dhcpclient"][0]["updns"]) != cpmmodule.params["ipv4dhcpupdns"]): + total_change = (total_change | 256) + dhcpupdns.insert(protocol, to_native(cpmmodule.params["ipv4dhcpupdns"])) + + if cpmmodule.params["ipv4dhcpdefgateway"] is not None: + if (int(existing_interface["interface"][0]["ietf-ipv4"]["address"][0]["defgateway"]) != cpmmodule.params["ipv4dhcpdefgateway"]): + total_change = (total_change | 512) + dhcpdefgateway.insert(protocol, to_native(cpmmodule.params["ipv4dhcpdefgateway"])) + + protocol += 1 + + if cpmmodule.params["ipv6address"] is not None: + if (existing_interface["interface"][0]["ietf-ipv6"]["address"][0]["ip"] != cpmmodule.params["ipv6address"]): + total_change = (total_change | 2) + address.insert(protocol, to_native(cpmmodule.params["ipv6address"])) + + if cpmmodule.params["ipv6subnetprefix"] is not None: + if (existing_interface["interface"][0]["ietf-ipv6"]["address"][0]["netmask"] != cpmmodule.params["ipv6subnetprefix"]): + total_change = (total_change | 4) + netmask.insert(protocol, to_native(cpmmodule.params["ipv6subnetprefix"])) + + if cpmmodule.params["ipv6gateway"] is not None: + if (existing_interface["interface"][0]["ietf-ipv6"]["address"][0]["gateway"] != cpmmodule.params["ipv6gateway"]): + total_change = (total_change | 8) + gateway.insert(protocol, to_native(cpmmodule.params["ipv6gateway"])) + + if (total_change > 0): + protocol = protocolchanged = 0 + json_load = '{"interface": [ { "name": "%s"' % (to_native(cpmmodule.params["interface"])) + + if (negotiation is not None): + json_load = '%s,"negotiation": "%s"' % (json_load, negotiation) + + for protocol in range(0, 2): + protocolchanged = 0 + if ((address[protocol] is not None) or (netmask[protocol] is not None) or (gateway[protocol] is not None) or + (dhcpdefgateway[protocol] is not None)): + protocolchanged += 1 + ietfstring = "" + + if (address[protocol] is not None): + ietfstring = '%s"ip": "%s"' % (ietfstring, address[protocol]) + + if (netmask[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"netmask": "%s"' % (ietfstring, netmask[protocol]) + + if (gateway[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"gateway": "%s"' % (ietfstring, gateway[protocol]) + + if (dhcpdefgateway[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"defgateway": %s' % (ietfstring, dhcpdefgateway[protocol]) + + if (protocolchanged > 0): + if (protocol == 0): + json_load = '%s,"ietf-ipv4": { ' % (json_load) + else: + json_load = '%s,"ietf-ipv6": { ' % (json_load) + + json_load = '%s"address": [ {' % (json_load) + + json_load = '%s%s}]' % (json_load, ietfstring) + + if ((dhcphostname[protocol] is not None) or (dhcpenable[protocol] is not None) or (dhcplease[protocol] is not None) or + (dhcpobdns[protocol] is not None) or (dhcpupdns[protocol] is not None)): + if (protocolchanged == 0): + if (protocol == 0): + json_load = '%s,"ietf-ipv4": { ' % (json_load) + else: + json_load = '%s,"ietf-ipv6": { ' % (json_load) + else: + json_load = '%s,' % (json_load) + + protocolchanged += 1 + ietfstring = "" + json_load = '%s"dhcpclient": [ {' % (json_load) + + if (dhcpenable[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"enable": %s' % (ietfstring, dhcpenable[protocol]) + + if (dhcphostname[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"hostname": "%s"' % (ietfstring, dhcphostname[protocol]) + + if (dhcplease[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"lease": %s' % (ietfstring, dhcplease[protocol]) + + if (dhcpobdns[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"obdns": %s' % (ietfstring, dhcpobdns[protocol]) + + if (dhcpupdns[protocol] is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"updns": %s' % (ietfstring, dhcpupdns[protocol]) + + # end of dhcpclient + json_load = '%s%s}]' % (json_load, ietfstring) + + # end of ietf-ipv4 + if (protocolchanged > 0): + json_load = '%s}' % (json_load) + + # end of interface + json_load = '%s}]' % (json_load) + json_load = '%s}' % (json_load) + 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), + interface=dict(type='str', default=None, choices=["eth0", "eth1"]), + negotiation=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3, 4, 5, 6]), + ipv4address=dict(type='str', required=False, default=None), + ipv4netmask=dict(type='str', required=False, default=None), + ipv4gateway=dict(type='str', required=False, default=None), + ipv4dhcpenable=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4dhcphostname=dict(type='str', required=False, default=None), + ipv4dhcplease=dict(type='int', required=False, default=None), + ipv4dhcpobdns=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4dhcpupdns=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4dhcpdefgateway=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv6address=dict(type='str', required=False, default=None), + ipv6subnetprefix=dict(type='str', required=False, default=None), + ipv6gateway=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/interface?ports=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['interface']))) + 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'] = json.loads(response.read()) + payload = assemble_json(module, 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/interface?ports=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['interface']))) + 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() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_info.py new file mode 100644 index 00000000..c8c070eb --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_interface_info.py @@ -0,0 +1,195 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI Network Interface 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_interface_info +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get network interface parameters from WTI OOB and PDU devices +description: + - "Get network interface parameters from 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 + interface: + description: + - This is the ethernet port name that is getting retrieved. It can include a single ethernet + - port name, multiple ethernet port names separated by commas or not defined for all ports. + type: list + required: false + choices: [ "eth0", "eth1", "ppp0" ] +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the network interface Parameters for a WTI device for all interfaces + cpm_interface_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the network interface Parameters for a WTI device for a specific interface + cpm_interface_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + interface: "eth0,eth1" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + totalports: + description: Total ethernet ports requested of the WTI device. + returned: success + type: int + sample: 1 + interface: + description: Current k/v pairs of interface info for the WTI device after module execution. + returned: always + type: dict + sample: {"name": "eth1", "type": "0", "mac_address": "00-09-9b-02-45-db", "is_up": "0", "is_gig": "1", "speed": "10", "negotiation": "0", + "ietf-ipv4": {"address": [{"ip": "10.10.10.2","netmask": "255.255.255.0","gateway": ""}], + "dhcpclient": [{"enable": 0, "hostname": "", "lease": -1, "obdns": 1, "updns": 1}]}, + "ietf-ipv6": {"address": [{"ip": "", "netmask": "", "gateway": "" }]}} +""" + +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 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), + interface=dict(type='list', element='str', default=None, choices=["eth0", "eth1", "ppp0"]), + 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/interface" % (protocol, to_native(module.params['cpm_url']))) + ports = module.params['interface'] + + if (ports is not None): + if isinstance(ports, list): + ports = ','.join(to_native(x) for x in ports) + fullurl = ("%s?ports=%s" % (fullurl, ports)) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_config.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_config.py new file mode 100644 index 00000000..c9e90403 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_config.py @@ -0,0 +1,295 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 configure WTI network IPTables Parameters on 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_iptables_config +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Set network IPTables parameters in WTI OOB and PDU devices +description: + - "Set network IPTables 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 + protocol: + description: + - The protocol that the iptables entry should be applied. 0 = ipv4, 1 = ipv6. + type: int + required: false + choices: [ 0, 1 ] + index: + description: + - Index in which command should be inserted. If not defined entry will start at position one. + type: list + required: false + command: + description: + - Actual iptables command to send to the WTI device. + type: list + required: true + clear: + description: + - Removes all the iptables for the protocol being defined before setting the newly defined entry. + type: int + required: false + choices: [ 0, 1 ] +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Set Network IPTables Parameters +- name: Set the an IPTables Parameter for a WTI device + cpm_iptables_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + command: "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT" + +# Sets multiple Network IPTables Parameters +- name: Set the IPTables Parameters a WTI device + cpm_iptables_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + index: + - 1 + - 2 + command: + - "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT" + - "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + iptables: + description: Current k/v pairs of interface info for the WTI device after module execution. + returned: always + type: dict + sample: [{ "eth0": { "ietf-ipv4": { "clear": 1, "entries": [ + { "entry": "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT", "index": "1" }, + {"entry": "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT", "index": "2" }]}}}] +""" + +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_interface): + total_change = total_commands = total_indices = 0 + is_clear = is_changed = protocol = 0 + negotiation = None + json_load = "" + ietfstring = "ietf-ipv4" + + indices = [] + commands = [] + + for x in range(0, 48): + indices.insert(x, None) + commands.insert(x, None) + + if (cpmmodule.params['clear'] is not None): + is_clear = int(cpmmodule.params['clear']) + + if (cpmmodule.params['protocol'] is not None): + protocol = int(cpmmodule.params['protocol']) + if (protocol == 1): + ietfstring = "ietf-ipv6" + + index = cpmmodule.params['index'] + if (index is not None): + if isinstance(index, list): + for x in index: + indices.insert(total_indices, (int(to_native(x))) - 1) + total_indices += 1 + + command = cpmmodule.params['command'] + if (command is not None): + if isinstance(command, list): + for x in command: + if (total_indices == 0): + commands.insert(total_commands, to_native(x)) + else: + commands.insert(indices[total_commands], to_native(x)) + total_commands += 1 + + if (total_indices > 0): + if (total_commands != total_indices): + return None + + for x in range(0, 48): + if (commands[x] is not None): + if ((existing_interface["iptables"][0]["eth0"][ietfstring]["entries"][x]["entry"] != commands[x]) or (is_clear == 1)): + if (is_changed > 0): + json_load = '%s,' % (json_load) + json_load = '%s{"entry": "%s","index": "%d"}' % (json_load, commands[x], (x + 1)) + is_changed += 1 + + if (is_changed > 0) or (is_clear > 0): + json_load = '{"iptables": [{"eth0": { "%s": { "clear": %d, "entries": [ %s ]}}}]}' % (ietfstring, is_clear, json_load) + + 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), + protocol=dict(type='int', required=False, default=0, choices=[0, 1]), + index=dict(type='list', element='int', required=False, default=None), + command=dict(type='list', element='str', required=True), + clear=dict(type='int', required=False, default=None, choices=[0, 1]), + 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: + transport = "https://" + else: + transport = "http://" + + fullurl = ("%s%s/api/v2/config/iptables" % (transport, 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'] = json.loads(response.read()) + payload = assemble_json(module, result['data']) + + if module.check_mode: + if (payload is not None) and (len(payload) > 0): + result['changed'] = True + else: + if (payload is not None) and (len(payload) > 0): + fullurl = ("%s%s/api/v2/config/iptables" % (transport, 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() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_info.py new file mode 100644 index 00000000..27a7163f --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_iptables_info.py @@ -0,0 +1,175 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI Network IPTables 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_iptables_info +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get network IPTABLES parameters from WTI OOB and PDU devices +description: + - "Get network IPTABLES parameters from 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the network IPTABLES Parameters for a WTI device. + cpm_interface_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the network IPTABLES Parameters for a WTI device. + cpm_interface_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + iptables: + description: Current k/v pairs of IPTABLES info for the WTI device after module execution. + returned: always + type: dict + sample: {"iptables": [{"eth0": {"ietf-ipv4": + [{"clear": 0, "entries": [{"entry": "test10", "index": "1"}, {"entry": "", "index": "2" }]}], + "ietf-ipv6": + [{"clear": 0, "entries": [{"entry": "test30", "index": "1"}, {"entry": "test40", "index": "2" }]}]}}]} +""" + +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 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), + 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/iptables" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugconfig.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugconfig.py new file mode 100644 index 00000000..4215edcb --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugconfig.py @@ -0,0 +1,272 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2018 Red Hat Inc. +# Copyright (C) 2018 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 Plug Configuration Commands on WTI OOB and PDU devices. +# WTI 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_plugconfig +version_added: "2.8" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get and Set Plug Parameters on WTI OOB and PDU power devices +description: + - "Get and Set Plug Parameters on WTI OOB and PDU devices" +options: + cpm_action: + description: + - This is the Action to send the module. + type: str + required: true + choices: [ "getplugconfig", "setplugconfig" ] + 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 + plug_id: + description: + - This is the plug number that is to be manipulated + - For the getplugconfig command, the plug_id 'all' will return the status of all the plugs the + - user has rights to access. + type: str + required: true + plug_name: + description: + - The new name of the Plug. + type: str + required: false + plug_bootdelay: + description: + - On a reboot command, this is the time when a plug will turn on power, after it has been turned off. + - 0='0.5 Secs', 1='1 Sec', 2='2 Sec', 3='5 Sec', 4='15 Sec', 5='30 Sec', 6='1 Min', 7='2 Mins', + - 8='3 Mins', 9='5 Mins'. + type: int + required: false + choices: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] + plug_default: + description: + - What the Plugs default state is when the device starts. 0 - Off, 1 - On. + type: int + required: false + choices: [ 0, 1 ] + plug_bootpriority: + description: + - Prioritizes which plug gets its state changed first. The lower the number the higher the priority. + - Valid value can from 1 to the maximum number of plugs of the WTI unit. + type: int + required: false +""" + +EXAMPLES = """ +# Get Plug parameters for all ports +- name: Get the Plug parameters for ALL ports of a WTI Power device + cpm_plugconfig: + cpm_action: "getplugconfig" + cpm_url: "rest.wti.com" + cpm_username: "restpower" + cpm_password: "restfulpowerpass12" + use_https: true + validate_certs: true + plug_id: "all" + +# Get Plug parameters for port 2 +- name: Get the Plug parameters for the given port of a WTI Power device + cpm_plugconfig: + cpm_action: "getplugconfig" + cpm_url: "rest.wti.com" + cpm_username: "restpower" + cpm_password: "restfulpowerpass12" + use_https: true + validate_certs: false + plug_id: "2" + +# Configure plug 5 +- name: Configure parameters for Plug 5 on a given WTI Power device + cpm_plugconfig: + cpm_action: "setplugconfig" + cpm_url: "rest.wti.com" + cpm_username: "restpower" + cpm_password: "restfulpowerpass12" + use_https: true + plug_id: "5" + plug_name: "NewPlugNameFive" + plug_bootdelay: "3" + plug_default: "0" + plug_bootpriority: "1" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +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, cpmresult): + json_load = "" + plugspassed = cpmmodule.params["plug_id"].split(",") + + for val in plugspassed: + if len(json_load) == 0: + json_load = '{"plugs": [' + else: + json_load = '%s,' % (json_load) + + json_load = '%s{"plug": "%s"' % (json_load, to_native(val)) + + if cpmmodule.params["plug_name"] is not None: + json_load = '%s,"plugname": "%s"' % (json_load, to_native(cpmmodule.params["plug_name"])) + if cpmmodule.params["plug_bootdelay"] is not None: + json_load = '%s,"bootdelay": "%s"' % (json_load, to_native(cpmmodule.params["plug_bootdelay"])) + if cpmmodule.params["plug_default"] is not None: + json_load = '%s,"default": "%s"' % (json_load, to_native(cpmmodule.params["plug_default"])) + if cpmmodule.params["plug_bootpriority"] is not None: + json_load = '%s,"bootpriority": "%s"' % (json_load, to_native(cpmmodule.params["plug_bootpriority"])) + + json_load = '%s}' % (json_load) + + if len(json_load) > 0: + json_load = '%s]}' % (json_load) + + return json_load + + +def run_module(): + + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_action=dict(choices=['getplugconfig', 'setplugconfig'], required=True), + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + plug_id=dict(type='str', required=True), + plug_name=dict(type='str', required=False), + plug_bootdelay=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + plug_default=dict(type='int', required=False, default=None, choices=[0, 1]), + plug_bootpriority=dict(type='int', 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='', + debug='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + if module.check_mode: + return result + + 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://" + + Payload = None + if (module.params['cpm_action'] == 'getplugconfig'): + fullurl = ("%s%s/api/v2/config/powerplugconfig" % (protocol, to_native(module.params['cpm_url']))) + if (module.params['plug_id'].lower() != 'all'): + fullurl = '%s?plug=%s' % (fullurl, to_native(module.params['plug_id'])) + method = 'GET' + elif (module.params['cpm_action'] == 'setplugconfig'): + Payload = assemble_json(module, result) + result['debug'] = Payload + fullurl = ("%s%s/api/v2/config/powerplugconfig" % (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}) + if (method != 'GET'): + result['changed'] = True + + except HTTPError as e: + fail_json = dict(msg='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='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='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='Error connecting to for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugcontrol.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugcontrol.py new file mode 100644 index 00000000..5d62759f --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_plugcontrol.py @@ -0,0 +1,234 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2018 Red Hat Inc. +# Copyright (C) 2018 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 Plug Commands on WTI OOB and PDU devices. +# WTI 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_plugcontrol +version_added: "2.8" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get and Set Plug actions on WTI OOB and PDU power devices +description: + - "Get and Set Plug actions on WTI OOB and PDU devices" +options: + cpm_action: + description: + - This is the Action to send the module. + type: str + required: true + choices: [ "getplugcontrol", "setplugcontrol" ] + 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 + plug_id: + description: + - This is the plug number or the plug name that is to be manipulated + - For the plugget command, the plug_id 'all' will return the status of all the plugs the + - user has rights to access. + type: str + required: true + plug_state: + description: + - This is what action to take on the plug. + type: str + required: false + choices: [ "on", "off", "boot", "default" ] +""" + +EXAMPLES = """ +# Get Plug status for all ports +- name: Get the Plug status for ALL ports of a WTI device + cpm_plugcontrol: + cpm_action: "getplugcontrol" + cpm_url: "rest.wti.com" + cpm_username: "restpower" + cpm_password: "restfulpowerpass12" + use_https: true + validate_certs: true + plug_id: "all" + +# Get Plug status for port 2 +- name: Get the Plug status for the given port of a WTI device + cpm_plugcontrol: + cpm_action: "getplugcontrol" + cpm_url: "rest.wti.com" + cpm_username: "restpower" + cpm_password: "restfulpowerpass12" + use_https: true + validate_certs: false + plug_id: "2" + +# Reboot plug 5 +- name: Reboot Plug 5 on a given WTI device + cpm_plugcontrol: + cpm_action: "setplugcontrol" + cpm_url: "rest.wti.com" + cpm_username: "restpower" + cpm_password: "restfulpowerpass12" + use_https: true + plug_id: "5" + plug_state: "boot" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +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, cpmresult): + json_load = "" + plugspassed = cpmmodule.params["plug_id"].split(",") + + for val in plugspassed: + if (val.isdigit() is True): + json_load = '%s{"plug": "%s"' % (json_load, to_native(val)) + else: + json_load = '%s{"plugname": "%s"' % (json_load, to_native(val)) + + if cpmmodule.params["plug_state"] is not None: + json_load = '%s,"state": "%s"' % (json_load, to_native(cpmmodule.params["plug_state"])) + + json_load = '%s}' % (json_load) + + return json_load + + +def run_module(): + + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_action=dict(choices=['getplugcontrol', 'setplugcontrol'], required=True), + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + plug_id=dict(type='str', required=True), + plug_state=dict(choices=['on', 'off', 'boot', 'default'], required=False), + 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) + + if module.check_mode: + return result + + 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://" + + Payload = None + if (module.params['cpm_action'] == 'getplugcontrol'): + fullurl = ("%s%s/api/v2/config/powerplug" % (protocol, to_native(module.params['cpm_url']))) + if (module.params['plug_id'].lower() != 'all'): + fullurl = '%s?plug=%s' % (fullurl, to_native(module.params['plug_id'])) + method = 'GET' + elif (module.params['cpm_action'] == 'setplugcontrol'): + Payload = assemble_json(module, result) + fullurl = ("%s%s/api/v2/config/powerplug" % (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}) + if (method != 'GET'): + result['changed'] = True + + except HTTPError as e: + fail_json = dict(msg='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='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='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='Error connecting to for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_power_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_power_info.py new file mode 100644 index 00000000..163d9511 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_power_info.py @@ -0,0 +1,242 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI Power information 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_power_info +version_added: "2.9" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get the Power Information of a WTI device +description: + - "Get the Power Information of a WTI device" +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 + cpm_startdate: + description: + - Start date of the range to look for power data + type: str + required: false + cpm_enddate: + description: + - End date of the range to look for power data + type: str + required: false + 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Power Information of a WTI device + cpm_power_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Power Information of a WTI device + cpm_power_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false + startdate: 01-12-2020" + enddate: 02-16-2020" +""" + +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: "2020-02-24T20:54:03+00:00" + powerunit: + description: Identifies if the WTI device is a power type device. + returned: success + type: str + sample: "1" + outletmetering: + description: Identifies if the WTI device has Poiwer Outlet metering. + returned: success + type: str + sample: "1" + ats: + description: Identifies if the WTI device is an ATS type of power device. + returned: success + type: str + sample: "1" + plugcount: + description: Current outlet plug count of the WTI device after module execution. + returned: success + type: str + sample: "8" + powerfactor: + description: Power factor of the WTI device after module execution. + returned: success + type: str + sample: "100" + powereff: + description: Power efficiency of the WTI device after module execution. + returned: success + type: str + sample: "100" + powerdatacount: + description: Total powerdata samples returned after module execution. + returned: success + type: str + sample: "1" + powerdata: + description: Power data of the WTI device after module execution. + returned: success + type: dict + sample: [ { "timestamp": "2020-02-24T21:45:18+00:00", + "branch1": [{ "voltage1": "118.00","current1": "0.00","current2": "0.00","current3": "0.00","current4": "0.00", + "current5": "0.00","current6": "0.00","current7": "0.00","current8": "0.00"}] }] + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +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 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), + cpm_startdate=dict(type='str', required=False), + cpm_enddate=dict(type='str', required=False), + 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://" + + additional = "" + + if module.params['cpm_startdate'] is not None and (len(to_native(module.params['cpm_startdate'])) > 0): + if module.params['cpm_enddate'] is not None and (len(to_native(module.params['cpm_enddate'])) > 0): + additional = "?startdate=%s&enddate=%s" % (to_native(module.params['cpm_startdate']), to_native(module.params['cpm_enddate'])) + + fullurl = ("%s%s/api/v2/status/power" % (protocol, to_native(module.params['cpm_url']))) + + if (len(additional) > 0): + fullurl += additional + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_config.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_config.py new file mode 100644 index 00000000..88dd74f0 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_config.py @@ -0,0 +1,360 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 Serial Port Parameters on 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_serial_port_config +version_added: "2.9" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Set Serial port parameters in WTI OOB and PDU devices +description: + - "Set Serial port 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 + port: + description: + - This is the port number that is getting the action performed on. + type: int + required: true + portname: + description: + - This is the Name of the Port that is displayed. + type: str + required: false + baud: + description: + - This is the baud rate to assign to the port. + - 0=300, 1=1200, 2=2400, 3=4800, 4=9600, 5=19200, 6=38400, 7=57600, 8=115200, 9=230400, 10=460800 + type: int + required: false + choices: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] + handshake: + description: + - This is the handshake to assign to the port, 0=None, 1=XON/XOFF, 2=RTS/CTS, 3=Both. + type: int + required: false + choices: [ 0, 1, 2, 3 ] + stopbits: + description: + - This is the stop bits to assign to the port, 0=1 Stop Bit, 1=2 Stop Bit. + type: int + required: false + choices: [ 0, 1 ] + parity: + description: + - This is the parity to assign to the port, 0=7-None, 1=7-Even, 2=7-Odd, 3=8-None, 4=8-Even, 5=8-Odd. + type: int + required: false + choices: [ 0, 1, 2, 3, 4, 5 ] + mode: + description: + - This is the port mode to assign to the port, 0=Any-to-Any. 1=Passive, 2=Buffer, 3=Modem, 4=ModemPPP. + type: int + required: false + choices: [ 0, 1, 2, 3, 4 ] + cmd: + description: + - This is the Admin Mode to assign to the port, 0=Deny, 1=Permit. + type: int + required: false + choices: [ 0, 1 ] + seq: + description: + - This is the type of Sequence Disconnect to assign to the port, 0=Three Characters (before and after), 1=One Character Only, 2=Off + type: int + required: false + choices: [ 1, 2, 3 ] + tout: + description: + - This is the Port Activity Timeout to assign to the port, 0=Off, 1=5 Min, 2=15 Min, 3=30 Min, 4=90 Min, 5=1 Min. + type: int + required: false + choices: [ 0, 1, 2, 3, 4, 5 ] + echo: + description: + -This is the command echo parameter to assign to the port, 0=Off, 1=On + type: bool + required: false + break_allow: + description: + - This is if the break character is allowed to be passed through the port, 0=Off, 1=On + type: bool + required: false + logoff: + description: + - This is the logout character to assign to the port + - If preceded by a ^ character, the sequence will be a control character. Used if seq is set to 0 or 1 + type: str + required: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Set Serial Port Parameters +- name: Set the Port Parameters for port 2 of a WTI device + cpm_serial_port_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + port: "2" + portname: "RouterLabel" + baud: "7" + handshake: "1" + stopbits: "0" + parity: "0" + mode: "0" + cmd: "0" + seq: "1" + tout: "1" + echo: "0" + break_allow: "0" + logoff: "^H" + +# Set Serial Port Port Name and Baud Rate Parameters +- name: Set New port name and baud rate (115k) for port 4 of a WTI device + cpm_serial_port_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + port: "4" + portname: "NewPortName1" + baud: "8" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +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_serial): + total_change = 0 + + json_load = '{"serialports":{"port": "%s"' % to_native(cpmmodule.params["port"]) + + if cpmmodule.params["portname"] is not None: + if (existing_serial["serialports"][0]["portname"] != to_native(cpmmodule.params["portname"])): + total_change = (total_change | 1) + json_load = '%s,"portname": "%s"' % (json_load, to_native(cpmmodule.params["portname"])) + if cpmmodule.params["baud"] is not None: + if (existing_serial["serialports"][0]["baud"] != to_native(cpmmodule.params["baud"])): + total_change = (total_change | 2) + json_load = '%s,"baud": %s' % (json_load, to_native(cpmmodule.params["baud"])) + if cpmmodule.params["handshake"] is not None: + if (existing_serial["serialports"][0]["handshake"] != to_native(cpmmodule.params["handshake"])): + total_change = (total_change | 4) + json_load = '%s,"handshake": %s' % (json_load, to_native(cpmmodule.params["handshake"])) + if cpmmodule.params["stopbits"] is not None: + if (existing_serial["serialports"][0]["stopbits"] != to_native(cpmmodule.params["stopbits"])): + total_change = (total_change | 8) + json_load = '%s,"stopbits": %s' % (json_load, to_native(cpmmodule.params["stopbits"])) + if cpmmodule.params["parity"] is not None: + if (existing_serial["serialports"][0]["parity"] != to_native(cpmmodule.params["parity"])): + total_change = (total_change | 16) + json_load = '%s,"parity": %s' % (json_load, to_native(cpmmodule.params["parity"])) + if cpmmodule.params["mode"] is not None: + if (existing_serial["serialports"][0]["mode"] != to_native(cpmmodule.params["mode"])): + total_change = (total_change | 32) + json_load = '%s,"mode": %s' % (json_load, to_native(cpmmodule.params["mode"])) + if cpmmodule.params["cmd"] is not None: + if (existing_serial["serialports"][0]["cmd"] != to_native(cpmmodule.params["cmd"])): + total_change = (total_change | 64) + json_load = '%s,"cmd": %s' % (json_load, to_native(cpmmodule.params["cmd"])) + if cpmmodule.params["seq"] is not None: + if (existing_serial["serialports"][0]["seq"] != to_native(cpmmodule.params["seq"])): + total_change = (total_change | 128) + json_load = '%s,"seq": %s' % (json_load, to_native(cpmmodule.params["seq"])) + if cpmmodule.params["tout"] is not None: + if (existing_serial["serialports"][0]["tout"] != to_native(cpmmodule.params["tout"])): + total_change = (total_change | 256) + json_load = '%s,"tout": %s' % (json_load, to_native(cpmmodule.params["tout"])) + if cpmmodule.params["echo"] is not None: + if (int(existing_serial["serialports"][0]["echo"]) != int(cpmmodule.params["echo"])): + total_change = (total_change | 512) + json_load = '%s,"echo": %d' % (json_load, int(cpmmodule.params["echo"])) + if cpmmodule.params["break_allow"] is not None: + if (int(existing_serial["serialports"][0]["break"]) != int(cpmmodule.params["break_allow"])): + total_change = (total_change | 1024) + json_load = '%s,"break": %d' % (json_load, int(cpmmodule.params["break_allow"])) + if cpmmodule.params["logoff"] is not None and (len(cpmmodule.params["logoff"]) > 0): + if (existing_serial["serialports"][0]["logoff"] != to_native(cpmmodule.params["logoff"])): + total_change = (total_change | 2048) + json_load = '%s,"logoff": "%s"' % (json_load, to_native(cpmmodule.params["logoff"])) + + json_load = '%s}}' % (json_load) + + if (total_change == 0): + 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), + port=dict(type='int', required=True), + portname=dict(type='str', required=False, default=None), + baud=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), + handshake=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3]), + stopbits=dict(type='int', required=False, default=None, choices=[0, 1]), + parity=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3, 4, 5]), + mode=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3, 4]), + cmd=dict(type='int', required=False, default=None, choices=[0, 1]), + seq=dict(type='int', required=False, default=None, choices=[1, 2, 3]), + tout=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3, 4, 5]), + echo=dict(type='bool', required=False, default=None), + break_allow=dict(type='bool', required=False), + logoff=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/serialports?ports=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['port']))) + 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'] = json.loads(response.read()) + payload = assemble_json(module, 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/serialports" % (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() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_info.py new file mode 100644 index 00000000..5cfd0611 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_info.py @@ -0,0 +1,221 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI Serial Port 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_serial_port_info +version_added: "2.9" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get Serial port parameters in WTI OOB and PDU devices +description: + - "Get Serial port parameters from 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: false + 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: false + use_proxy: + description: Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false + port: + description: + - This is the serial port number that is getting retrieved. It can include a single port + - number, multiple port numbers separated by commas, a list of port numbers, or an '*' character for all ports. + type: list + required: true + default: ['*'] +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Serial Port Parameters for port 2 of a WTI device + cpm_serial_port_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + port: 2 + +- name: Get the Serial Port Parameters for ports 2 and 4 of a WTI device + cpm_serial_port_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + port: 2,4 + +- name: Get the Serial Port Parameters for all ports of a WTI device + cpm_serial_port_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + port: "*" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + serialports: + description: List of data for each serial port + returned: success + type: list + sample: + - baud: 4 + break: 1 + cmd: 1 + connstatus: Free + echo: 1 + handshake: 2 + logoff: '^X' + mode: 1 + parity: 3 + port: 2 + portname: switch + seq: 2 + stopbits: 1 + tout: 0 + + - baud: 3 + break: 1 + cmd: 1 + connstatus: Free + echo: 1 + handshake: 2 + logoff: '^X' + mode: 1 + parity: 1 + port: 4 + portname: router + seq: 2 + stopbits: 1 + tout: 1 +""" + +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 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), + port=dict(type='list', default=['*']), + use_https=dict(type='bool', default=False), + validate_certs=dict(type='bool', default=False), + 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://" + + ports = module.params['port'] + if isinstance(ports, list): + ports = ','.join(to_native(x) for x in ports) + fullurl = ("%s%s/api/v2/config/serialports?ports=%s" % (protocol, to_native(module.params['cpm_url']), ports)) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_config.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_config.py new file mode 100644 index 00000000..5b9764e6 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_config.py @@ -0,0 +1,603 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 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 configure WTI network SNMP Parameters on 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_snmp_config +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Set network IPTables parameters in WTI OOB and PDU devices +description: + - "Set network IPTables 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 + protocol: + description: + - The protocol that the SNMP entry should be applied. 0 = ipv4, 1 = ipv6. + type: int + required: false + choices: [ 0, 1 ] + enable: + description: + - The activates SNMP polling for the specified interface and protocol. + type: int + required: false + choices: [ 0, 1 ] + interface: + description: + - The ethernet port for the SNMP we are defining. + type: str + required: false + choices: [ "eth0", "eth1", "ppp0" ] + readonly: + description: + - Controls the ability to change configuration parameters with SNMP. + type: int + required: false + choices: [ 0, 1 ] + version: + description: + - Defined which version of SNMP the device will respond to 0 = V1/V2 Only, 1 = V3 Only, 2 = V1/V2/V3. + type: int + required: false + choices: [ 0, 1, 2 ] + contact: + description: + - The name of the administrator responsible for SNMP issues. + type: str + required: false + location: + description: + - The location of the SNMP Server. + type: str + required: false + systemname: + description: + - The hostname of the WTI Device. + type: str + required: false + rocommunity: + description: + - Read Only Community Password, not used for SNMP V3. + type: str + required: false + rwcommunity: + description: + - Read/Write Community Password, not used for SNMP V3. + type: str + required: false + clear: + description: + - Removes all the users for the protocol being defined before setting the newly defined entries. + type: int + required: false + choices: [ 0, 1 ] + index: + description: + - Index of the user being modified (V3 only). + type: list + required: false + username: + description: + - Sets the User Name for SNMPv3 access (V3 only). + type: list + required: false + authpriv: + description: + - Configures the Authentication and Privacy features for SNMPv3 communication, 0 = Auth/NoPriv, 1 = Auth/Priv (V3 only). + type: list + required: false + authpass: + description: + - Sets the Authentication Password for SNMPv3 (V3 only). + type: list + required: false + authproto: + description: + - Which authentication protocol will be used, 0 = MD5, 1 = SHA1 (V3 only). + type: list + required: false + privpass: + description: + - Sets the Privacy Password for SNMPv3 (V3 only) (V3 only). + type: list + required: false + privproto: + description: + - Which privacy protocol will be used, 0 = DES, 1 = AES128 (V3 only). + type: list + required: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Sets the device SNMP Parameters +- name: Set the an SNMP Parameter for a WTI device + cpm_iptables_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + interface: "eth0" + use_https: true + validate_certs: false + protocol: 0 + clear: 1 + enable: 1 + readonly: 0 + version: 0 + rocommunity: "ropassword" + rwcommunity: "rwpassword" + +# Sets the device SNMP Parameters +- name: Set the SNMP Parameters a WTI device + cpm_iptables_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + version: 1 + index: + - 1 + - 2 + username: + - "username1" + - "username2" + authpriv: + - 1 + - 1 + authpass: + - "authpass1" + - "uthpass2" + authproto: + - 1 + - 1 + privpass: + - "authpass1" + - "uthpass2" + privproto: + - 1 + - 1 +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + snmpaccess: + description: Current k/v pairs of interface info for the WTI device after module execution. + returned: always + type: dict + sample: [{ "eth0": { "ietf-ipv4": { "clear": 1, "enable": 0, "readonly": 0, "version": 0, "users": [ + { "username": "username1", "authpass": "testpass", "authpriv": "1", "authproto": "0", "privpass": "privpass1", + "privproto": "0", "index": "1" }]}}}] +""" + +from collections import OrderedDict +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_interface): + total_username = total_indices = 0 + is_clear = is_changed = protocol = loop = 0 + json_load = "" + ietfstring = "ietf-ipv4" + snmpenable = snmpversion = snmpreadonly = None + snmpsystemname = None + snmpcontact = None + snmplocation = None + snmprocommunity = None + snmprwcommunity = None + user_load = "" + + indices = [] + usernamearray = [] + authpriv = [] + authpassarray = [] + authproto = [] + privpassarray = [] + privproto = [] + + for x in range(0, 48): + indices.insert(x, None) + usernamearray.insert(x, None) + authpriv.insert(x, None) + authpassarray.insert(x, None) + authproto.insert(x, None) + privpassarray.insert(x, None) + privproto.insert(x, None) + + ports = cpmmodule.params['interface'] + + if (cpmmodule.params['clear'] is not None): + is_clear = int(cpmmodule.params['clear']) + + if (cpmmodule.params['protocol'] is not None): + protocol = int(cpmmodule.params['protocol']) + if (protocol == 1): + ietfstring = "ietf-ipv6" + + if (cpmmodule.params['enable'] is not None): + snmpenable = int(cpmmodule.params['enable']) + + if (cpmmodule.params['version'] is not None): + snmpversion = int(cpmmodule.params['version']) + + if (cpmmodule.params['readonly'] is not None): + snmpreadonly = int(cpmmodule.params['readonly']) + + if (cpmmodule.params['systemname'] is not None): + snmpsystemname = to_native(cpmmodule.params['systemname']) + + if (cpmmodule.params['contact'] is not None): + snmpcontact = to_native(cpmmodule.params['contact']) + + if (cpmmodule.params['location'] is not None): + snmplocation = to_native(cpmmodule.params['location']) + + if (cpmmodule.params['rocommunity'] is not None): + snmprocommunity = to_native(cpmmodule.params['rocommunity']) + + if (cpmmodule.params['rwcommunity'] is not None): + snmprwcommunity = to_native(cpmmodule.params['rwcommunity']) + + index = cpmmodule.params['index'] + if (index is not None): + if isinstance(index, list): + for x in index: + indices.insert(total_indices, (int(to_native(x))) - 1) + total_indices += 1 + + ii = 0 + index = cpmmodule.params['authpriv'] + if (index is not None): + if isinstance(index, list): + for x in index: + authpriv.insert(ii, int(to_native(x))) + ii += 1 + + ii = 0 + index = cpmmodule.params['authproto'] + if (index is not None): + if isinstance(index, list): + for x in index: + authproto.insert(ii, int(to_native(x))) + ii += 1 + + ii = 0 + index = cpmmodule.params['privproto'] + if (index is not None): + if isinstance(index, list): + for x in index: + privproto.insert(ii, int(to_native(x))) + ii += 1 + + total_username = 0 + usernamearray = cpmmodule.params['username'] + if (usernamearray is not None): + if isinstance(usernamearray, list): + for x in usernamearray: + usernamearray[total_username] = to_native(x) + total_username += 1 + + ii = 0 + authpassarray = cpmmodule.params['authpass'] + if (authpassarray is not None): + if isinstance(authpassarray, list): + for x in authpassarray: + authpassarray[ii] = to_native(x) + ii += 1 + + ii = 0 + authpassarray = cpmmodule.params['authpass'] + if (authpassarray is not None): + if isinstance(authpassarray, list): + for x in authpassarray: + authpassarray[ii] = to_native(x) + ii += 1 + + ii = 0 + privpassarray = cpmmodule.params['privpass'] + if (privpassarray is not None): + if isinstance(privpassarray, list): + for x in privpassarray: + privpassarray[ii] = to_native(x) + ii += 1 + + if (total_indices > 0): + if (total_username != total_indices): + return None + + for x in range(0, total_username): + if (usernamearray[x] is not None): + if (loop > 0): + user_load = '%s,' % (user_load) + + user_load = '%s{"index": "%d"' % (user_load, (indices[x] + 1)) + + if (usernamearray[x] is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["username"] != usernamearray[x]): + is_changed = True + + user_load = '%s,"username": "%s"' % (user_load, usernamearray[x]) + else: + user_load = '%s,"username": "%s"' % (user_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["username"]) + + if (authpassarray[x] is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["authpass"] != authpassarray[x]): + is_changed = True + user_load = '%s,"authpass": "%s"' % (user_load, authpassarray[x]) + else: + user_load = '%s,"authpass": "%s"' % (user_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["authpass"]) + + if (privpassarray[x] is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["privpass"] != privpassarray[x]): + is_changed = True + user_load = '%s,"privpass": "%s"' % (user_load, privpassarray[x]) + else: + user_load = '%s,"privpass": "%s"' % (user_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["privpass"]) + + if (authpriv[x] is not None): + if (int(existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["authpriv"]) != int(authpriv[x])): + is_changed = True + user_load = '%s,"authpriv": "%s"' % (user_load, authpriv[x]) + else: + user_load = '%s,"authpriv": "%s"' % (user_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["authpriv"]) + + if (authproto[x] is not None): + if (int(existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["authproto"]) != int(authproto[x])): + is_changed = True + user_load = '%s,"authproto": "%s"' % (user_load, authproto[x]) + else: + user_load = '%s,"authproto": "%s"' % (user_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["authproto"]) + + if (privproto[x] is not None): + if (int(existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["privproto"]) != int(privproto[x])): + is_changed = True + user_load = '%s,"privproto": "%s"' % (user_load, privproto[x]) + else: + user_load = '%s,"privproto": "%s"' % (user_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["users"][(indices[x])]["privproto"]) + + user_load = '%s}' % (user_load) + loop += 1 + + if (loop > 0): + json_load = '{"snmpaccess": [{"%s": { "%s": { "clear": %d, "change": %d' % (ports, ietfstring, is_clear, is_changed) + + if (snmpenable is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["enable"] != snmpenable): + is_changed = True + json_load = '%s, "enable": %d' % (json_load, snmpenable) + else: + json_load = '%s,"enable": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["enable"]) + + if (snmpversion is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["version"] != snmpversion): + is_changed = True + json_load = '%s, "version": %d' % (json_load, snmpversion) + else: + json_load = '%s,"version": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["version"]) + + if (snmpreadonly is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["readonly"] != snmpreadonly): + is_changed = True + json_load = '%s, "readonly": %d' % (json_load, snmpreadonly) + else: + json_load = '%s,"readonly": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["readonly"]) + + if (snmpsystemname is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["systemname"] != snmpsystemname): + is_changed = True + json_load = '%s, "systemname": %d' % (json_load, snmpsystemname) + else: + json_load = '%s,"systemname": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["systemname"]) + + if (snmpcontact is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["contact"] != snmpcontact): + is_changed = True + json_load = '%s, "contact": %d' % (json_load, snmpcontact) + else: + json_load = '%s,"contact": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["contact"]) + + if (snmplocation is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["location"] != snmplocation): + is_changed = True + json_load = '%s, "location": %d' % (json_load, snmplocation) + else: + json_load = '%s,"location": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["location"]) + + if (snmprocommunity is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["rocommunity"] != snmprocommunity): + is_changed = True + json_load = '%s, "rocommunity": %d' % (json_load, snmprocommunity) + else: + json_load = '%s,"rocommunity": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["rocommunity"]) + + if (snmprwcommunity is not None): + if (existing_interface["snmpaccess"][0][ports][0][ietfstring]["rwcommunity"] != snmprwcommunity): + is_changed = True + json_load = '%s, "rwcommunity": %d' % (json_load, snmprwcommunity) + else: + json_load = '%s,"rwcommunity": "%s"' % (json_load, existing_interface["snmpaccess"][0][ports][0][ietfstring]["rwcommunity"]) + + if (len(user_load) > 0): + json_load = '%s, "users": [ %s ]' % (json_load, user_load) + + json_load = '%s}}}]}' % (json_load) + + return is_changed, 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), + interface=dict(type='str', required=True, choices=["eth0", "eth1", "ppp0"]), + protocol=dict(type='int', required=False, default=0, choices=[0, 1]), + clear=dict(type='int', required=False, default=None, choices=[0, 1]), + enable=dict(type='int', required=False, default=None, choices=[0, 1]), + version=dict(type='int', required=False, default=None, choices=[0, 1, 2]), + readonly=dict(type='int', required=False, default=None, choices=[0, 1]), + systemname=dict(type='str', element='str', required=False), + contact=dict(type='str', element='str', required=False), + location=dict(type='str', element='str', required=False), + rocommunity=dict(type='str', element='str', required=False), + rwcommunity=dict(type='str', element='str', required=False), + index=dict(type='list', element='int', required=False, default=None), + username=dict(type='list', element='str', required=True), + authpriv=dict(type='list', element='int', required=False, default=None), + authproto=dict(type='list', element='int', required=False, default=None), + privproto=dict(type='list', element='int', required=False, default=None), + authpass=dict(type='list', element='str', required=False), + privpass=dict(type='list', element='str', required=False), + 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: + transport = "https://" + else: + transport = "http://" + + fullurl = ("%s%s/api/v2/config/snmpaccess?ports=%s" % (transport, to_native(module.params['cpm_url']), to_native(module.params['interface']))) + 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) + + was_changed = False + result['data'] = json.loads(response.read()) + was_changed, payload = assemble_json(module, result['data']) +# result['data'] = payload + + if module.check_mode: + if (payload is not None) and (len(payload) > 0): + result['changed'] = True + else: + if (payload is not None) and (len(payload) > 0): + fullurl = ("%s%s/api/v2/config/snmpaccess" % (transport, 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'] = was_changed + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_info.py new file mode 100644 index 00000000..4826ea6b --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_snmp_info.py @@ -0,0 +1,193 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 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 retrieve WTI Network SNMP 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_snmp_info +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get network SNMP parameters from WTI OOB and PDU devices +description: + - "Get network SNMP parameters from 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 + interface: + description: + - This is the ethernet port name that is getting retrieved. It can include a single ethernet + - port name, multiple ethernet port names separated by commas or not defined for all ports. + type: str + required: false + choices: [ "eth0", "eth1", "ppp0" ] + 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the network SNMP Parameters for all interfaces of a WTI device. + cpm_interface_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + + +- name: Get the network SNMP Parameters for eth0 of a WTI device. + cpm_interface_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false + interface: "eth0" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + snmpaccess: + description: Current k/v pairs of SNMP info for the WTI device after module execution. + returned: always + type: dict + sample: {"snmpaccess": [{"eth0": {"ietf-ipv4": + [{"enable": 0, "users": [{"index": "1", "username": "test10", "authpriv": "1", "authpass": "testpass", + "authproto": "0", "privpass": "testpass", "privproto": "1"}]}], + "ietf-ipv6": + [{"enable": 0, "users": [{"index": "1", "username": "test10", "authpriv": "1", "authpass": "testpass", + "authproto": "0", "privpass": "testpass", "privproto": "1"}]}]}}]} +""" + +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 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), + interface=dict(type='str', default=None, choices=["eth0", "eth1", "ppp0"]), + 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/snmpaccess" % (protocol, to_native(module.params['cpm_url']))) + ports = module.params['interface'] + + if (ports is not None): + if isinstance(ports, list): + ports = ','.join(to_native(x) for x in ports) + fullurl = ("%s?ports=%s" % (fullurl, ports)) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_status_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_status_info.py new file mode 100644 index 00000000..e76c95d6 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_status_info.py @@ -0,0 +1,307 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI general status information 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_status_info +version_added: "2.9" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get general status information from WTI OOB and PDU devices +description: + - "Get temperature general status from 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Status Information for a WTI device + cpm_status_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Status Information for a WTI device + cpm_status_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + vendor: + description: Identifies WTI device as a WTI device. + returned: success + type: str + sample: "wti" + product: + description: Current Product Part Number of the WTI device. + returned: success + type: str + sample: "CPM-800-1-CA" + totalports: + description: Total serial ports of the WTI device. + returned: success + type: str + sample: "9" + totalplugs: + description: Total Power Outlet plugs of the WTI device. + returned: success + type: str + sample: "8" + option1/2: + description: Various Identity options of the WTI. + returned: success + type: str + sample: "WPO-STRT-CPM8 / W4G-VZW-CPM8" + softwareversion: + description: Expanded Firmware version of the WTI device. + returned: success + type: str + sample: "6.60 19 Feb 2020" + serialnumber: + description: Current Serial number of the WTI device. + returned: success + type: str + sample: "12345678901234" + assettag: + description: Current Asset Tag of the WTI device. + returned: success + type: str + sample: "ARTE121" + siteid: + description: Current Site-ID of the WTI device. + returned: success + type: str + sample: "GENEVARACK" + analogmodemphonenumber: + description: Current Analog Modem (if installed) Phone number of the WTI device. + returned: success + type: str + sample: "9495869959" + modeminstalled: + description: Identifies if a modem is installed in the WTI device. + returned: success + type: str + sample: "Yes, 4G/LTE" + modemmodel: + description: Identifies the modem model number (if installed) in the WTI device. + returned: success + type: str + sample: "MTSMC-LVW2" + gig_dualphy: + description: Identifies dual ethernet port and gigabyte ethernet ports in the WTI device. + returned: success + type: str + sample: "Yes, Yes" + cpu_boardprogramdate: + description: Current Board and Program date of the WTI device. + returned: success + type: str + sample: "ARM, 4-30-2019" + ram_flash: + description: Total RAM and FLASH installed in the WTI device.. + returned: success + type: str + sample: "512 MB, 128 MB" + lineinputcount_rating: + description: Identifies total power inlets and their power rating. + returned: success + type: str + sample: "1 , 20 Amps" + currentmonitor: + description: Identifies if the unit has current monitoring capabilites. + returned: success + type: str + sample: "Yes" + keylength: + description: Current key length of the WTI device. + returned: success + type: str + sample: "2048" + opensslversion: + description: Current OpenSSL version running on the WTI device. + returned: success + type: str + sample: "1.1.1d 10 Sep 2019" + opensshversion: + description: Current OpenSSH running on the WTI device. + returned: success + type: str + sample: "8.2p1" + apacheversion: + description: Current Apache Web version running on the WTI device. + returned: success + type: str + sample: "2.4.41" + apirelease: + description: Current Date of the API release of the WTI device. + returned: success + type: str + sample: "March 2020" + uptime: + description: Current uptime of the WTI device. + returned: success + type: str + sample: "259308.26" + energywise: + description: Current Energywise version of the WTI device. + returned: success + type: str + sample: "1.2.0" + restful: + description: Current RESTful version of the WTI device. + returned: success + type: str + sample: "v1.0, v2 (Mar20)" + interface_list: + description: Current ethernet ports of the WTI device. + returned: success + type: str + sample: "eth0" + macaddresses: + description: Current mac addresses of the WTI device. + returned: always + type: dict + sample: { "mac": "00-09-9b-02-9a-26" } + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +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 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), + 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/status/status" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_temp_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_temp_info.py new file mode 100644 index 00000000..b8bc8b94 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_temp_info.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI temperature information 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_temp_info +version_added: "2.9" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get temperature information from WTI OOB and PDU devices +description: + - "Get temperature information from 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + temperature: + description: Current Temperature of the WTI device after module execution. + returned: success + type: str + sample: "76" + format: + description: Current Temperature format (Celsius or Fahrenheit) of the WTI device after module execution. + returned: success + type: str + sample: "F" + timestamp: + description: Current timestamp of the WTI device after module execution. + returned: success + type: str + sample: "2020-02-24T20:54:03+00:00" + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +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 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), + 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/status/temperature" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_config.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_config.py new file mode 100644 index 00000000..28e9b971 --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_config.py @@ -0,0 +1,410 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 time date Parameters on 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_time_config +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Set Time/Date parameters in WTI OOB and PDU devices. +description: + - "Set Time/Date and NTP 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 + date: + description: + - Static date in the format of two digit month, two digit day, four digit year separated by a slash symbol. + type: str + required: false + time: + description: + - Static time in the format of two digit hour, two digit minute, two digit second separated by a colon symbol. + type: str + required: false + timezone: + description: + - This is timezone that is assigned to the WTI device. + type: int + required: false + ntpenable: + description: + - This enables or disables the NTP client service. + type: int + required: false + choices: [ 0, 1 ] + ipv4address: + description: + - Comma separated string of up to two addresses for a primary and secondary IPv4 base NTP server. + type: str + required: false + ipv6address: + description: + - Comma separated string of up to two addresses for a primary and secondary IPv6 base NTP server. + type: str + required: false + timeout: + description: + - Set the network timeout in seconds of contacting the NTP servers, valid options can be from 1-60. + type: int + required: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Set a static time/date and timezone of a WTI device +- name: Set known fixed time/date of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + date: "12/12/2019" + time: "09:23:46" + timezone: 5 + +# Enable NTP and set primary and seconday servers of a WTI device +- name: Set NTP primary and seconday servers of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + timezone: 5 + ntpenable: 1 + ipv4address: "129.6.15.28.pool.ntp.org" + timeout: 15 +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + date: + description: Current Date of the WTI device after module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description: Current Time of the WTI device after module execution. + returned: success + type: str + sample: "12:12:00" + timezone: + description: Current Timezone of the WTI device after module execution. + returned: success + type: int + sample: 5 + ntp: + description: Current k/v pairs of ntp info of the WTI device after module execution. + returned: always + type: dict + sample: {"enable": "0", + "ietf-ipv4": {"address": [{"primary": "192.168.0.169","secondary": "12.34.56.78"}]}, + "ietf-ipv6": {"address": [{"primary": "","secondary": ""}]}, + "timeout": "4"} +""" + +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 = "" + + localdate = localtime = localtimezone = localenable = localtimeout = None + + localprimary = [] + localsecondary = [] + + for x in range(0, 2): + localprimary.insert(x, None) + localsecondary.insert(x, None) + + if cpmmodule.params["date"] is not None: + if (existing["date"] != to_native(cpmmodule.params["date"])): + total_change = (total_change | 1) + localdate = to_native(cpmmodule.params["date"]) + if cpmmodule.params["time"] is not None: + if (existing["time"] != to_native(cpmmodule.params["time"])): + total_change = (total_change | 2) + localtime = to_native(cpmmodule.params["time"]) + if cpmmodule.params["timezone"] is not None: + if (existing["timezone"] != to_native(cpmmodule.params["timezone"])): + total_change = (total_change | 4) + localtimezone = to_native(cpmmodule.params["timezone"]) + if cpmmodule.params["ntpenable"] is not None: + if (existing["ntp"]["enable"] != to_native(cpmmodule.params["ntpenable"])): + total_change = (total_change | 16) + localenable = to_native(cpmmodule.params["ntpenable"]) + if cpmmodule.params["ipv4address"] is not None: + loopcounter = 0 + portspassed = cpmmodule.params["ipv4address"].split(",") + for val in portspassed: + if (loopcounter == 0): + if (existing["ntp"]["ietf-ipv4"]["address"][0]["primary"] != to_native(val)): + total_change = (total_change | 32) + localprimary[0] = to_native(val) + loopcounter += 1 + else: + if (existing["ntp"]["ietf-ipv4"]["address"][0]["secondary"] != to_native(val)): + total_change = (total_change | 32) + localsecondary[0] = to_native(val) + loopcounter += 1 + if cpmmodule.params["ipv6address"] is not None: + loopcounter = 0 + portspassed = cpmmodule.params["ipv6address"].split(",") + for val in portspassed: + if (loopcounter == 0): + if (existing["ntp"]["ietf-ipv6"]["address"][0]["primary"] != to_native(val)): + total_change = (total_change | 64) + localprimary[1] = to_native(val) + loopcounter += 1 + else: + if (existing["ntp"]["ietf-ipv6"]["address"][0]["secondary"] != to_native(val)): + total_change = (total_change | 64) + localsecondary[1] = to_native(val) + loopcounter += 1 + if cpmmodule.params["timeout"] is not None: + if (existing["ntp"]["timeout"] != to_native(cpmmodule.params["timeout"])): + if ((int(to_native(cpmmodule.params["timeout"])) > 0) and (int(to_native(cpmmodule.params["timeout"])) <= 60)): + total_change = (total_change | 8) + localtimeout = to_native(cpmmodule.params["timeout"]) + + if (total_change > 0): + protocol = protocolchanged = 0 + ietfstring = "" + + if (localdate is not None): + ietfstring = '%s"date": "%s"' % (ietfstring, localdate) + + if (localtime is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"time": "%s"' % (ietfstring, localtime) + + if (localtimezone is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"timezone": "%s"' % (ietfstring, localtimezone) + + if ((localenable is not None) or (localtimeout is not None) or + (localprimary[0] is not None) or (localsecondary[0] is not None) or + (localprimary[1] is not None) or (localsecondary[1] is not None)): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "ntp": {' % (ietfstring) + + if (localenable is not None): + ietfstring = '%s"enable": "%s"' % (ietfstring, localenable) + + if (localtimeout is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"timeout": "%s"' % (ietfstring, localtimeout) + + if ((localprimary[0] is not None) or (localsecondary[0] is not None)): + if ((localenable is not None) or (localtimeout is not None)): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "ietf-ipv4": { "address": [{' % (ietfstring) + + if (localprimary[0] is not None): + ietfstring = '%s "primary": "%s"' % (ietfstring, localprimary[0]) + + if (localsecondary[0] is not None): + if (localprimary[0] is not None): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "secondary": "%s"' % (ietfstring, localsecondary[0]) + + # end ietf-ipv4 block + ietfstring = '%s }]}' % (ietfstring) + + if ((localprimary[1] is not None) or (localsecondary[1] is not None)): + if ((localprimary[0] is not None) or (localsecondary[0] is not None) or + (localenable is not None) or (localtimeout is not None)): + ietfstring = '%s,' % (ietfstring) + + ietfstring = '%s "ietf-ipv6": { "address": [{' % (ietfstring) + + if (localprimary[1] is not None): + ietfstring = '%s "primary": "%s"' % (ietfstring, localprimary[1]) + + if (localsecondary[1] is not None): + if (localprimary[1] is not None): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "secondary": "%s"' % (ietfstring, localsecondary[1]) + + # end ietf-ipv6 block + ietfstring = '%s }]}' % (ietfstring) + # end ntp block + ietfstring = '%s}' % (ietfstring) + + json_load = "{" + 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), + date=dict(type='str', required=False, default=None), + time=dict(type='str', required=False, default=None), + timezone=dict(type='int', required=False, default=None), + ntpenable=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4address=dict(type='str', required=False, default=None), + ipv6address=dict(type='str', required=False, default=None), + timeout=dict(type='int', 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/timedate" % (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/timedate" % (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() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_info.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_info.py new file mode 100644 index 00000000..ba03fd8f --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_time_info.py @@ -0,0 +1,190 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 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 retrieve WTI time date 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_time_info +version_added: "2.10" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get Time/Date parameters in WTI OOB and PDU devices +description: + - "Get Time/Date and NTP parameters from 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 +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + date: + description: Current Date of the WTI device after module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description: Current Time of the WTI device after module execution. + returned: success + type: str + sample: "12:12:00" + timezone: + description: Current Timezone of the WTI device after module execution. + returned: success + type: int + sample: 5 + ntp: + description: Current k/v pairs of ntp info of the WTI device after module execution. + returned: always + type: dict + sample: {"enable": "0", + "ietf-ipv4": {"address": [{"primary": "192.168.0.169","secondary": "12.34.56.78"}]}, + "ietf-ipv6": {"address": [{"primary": "","secondary": ""}]}, + "timeout": "4"} +""" + +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 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), + 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/timedate" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', 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'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_user.py b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_user.py new file mode 100644 index 00000000..8a3fbfbd --- /dev/null +++ b/collections-debian-merged/ansible_collections/wti/remote/plugins/modules/cpm_user.py @@ -0,0 +1,355 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2018 Red Hat Inc. +# Copyright (C) 2018 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 CPM User Commands on 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_user +version_added: "2.7" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get various status and parameters from WTI OOB and PDU devices +description: + - "Get/Add/Edit Delete Users from WTI OOB and PDU devices" +options: + cpm_action: + description: + - This is the Action to send the module. + required: true + type: str + choices: [ "getuser", "adduser", "edituser", "deleteuser" ] + 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 Basic Authentication Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Basic Authentication 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. + required: false + default: true + type: bool + 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 + user_name: + description: + - This is the User Name that needs to be create/modified/deleted + type: str + required: true + user_pass: + description: + - This is the User Password that needs to be create/modified/deleted + - If the user is being Created this parameter is required + type: str + required: false + user_accesslevel: + description: + - This is the access level that needs to be create/modified/deleted + - 0 View, 1 User, 2 SuperUser, 3 Administrator + type: int + required: false + choices: [ 0, 1, 2, 3 ] + user_accessssh: + description: + - If the user has access to the WTI device via SSH + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessserial: + description: + - If the user has access to the WTI device via Serial ports + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessweb: + description: + - If the user has access to the WTI device via Web + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessapi: + description: + - If the user has access to the WTI device via RESTful APIs + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessmonitor: + description: + - If the user has ability to monitor connection sessions + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessoutbound: + description: + - If the user has ability to initiate Outbound connection + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_portaccess: + description: + - If AccessLevel is lower than Administrator, which ports the user has access + type: str + required: false + user_plugaccess: + description: + - If AccessLevel is lower than Administrator, which plugs the user has access + type: str + required: false + user_groupaccess: + description: + - If AccessLevel is lower than Administrator, which Groups the user has access + type: str + required: false + user_callbackphone: + description: + - This is the Call Back phone number used for POTS modem connections + type: str + required: false + """ + +EXAMPLES = """ +# Get User Parameters +- name: Get the User Parameters for the given user of a WTI device + cpm_user: + cpm_action: "getuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" + +# Create User +- name: Create a User on a given WTI device + cpm_user: + cpm_action: "adduser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "complicatedpassword" + user_accesslevel: 2 + user_accessssh: 1 + user_accessserial: 1 + user_accessweb: 0 + user_accessapi: 1 + user_accessmonitor: 0 + user_accessoutbound: 0 + user_portaccess: "10011111" + user_plugaccess: "00000111" + user_groupaccess: "00000000" + +# Edit User +- name: Edit a User on a given WTI device + cpm_user: + cpm_action: "edituser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "newpasswordcomplicatedpassword" + +# Delete User +- name: Delete a User from a given WTI device + cpm_user: + cpm_action: "deleteuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +import base64 + +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): + json_load = '{"users":{"username": "%s"' % to_native((cpmmodule.params["user_name"])) + + # for Adding there must be a password present + if cpmmodule.params["user_pass"] is not None and (len(cpmmodule.params["user_pass"]) > 0): + json_load = '%s,"newpasswd": "%s"' % (json_load, to_native(cpmmodule.params["user_pass"])) + if cpmmodule.params["user_accesslevel"] is not None: + json_load = '%s,"accesslevel": %s' % (json_load, to_native(cpmmodule.params["user_accesslevel"])) + if cpmmodule.params["user_portaccess"] is not None: + json_load = '%s,"portaccess": %s' % (json_load, to_native(cpmmodule.params["user_portaccess"])) + if cpmmodule.params["user_plugaccess"] is not None: + json_load = '%s,"plugaccess": %s' % (json_load, to_native(cpmmodule.params["user_plugaccess"])) + if cpmmodule.params["user_groupaccess"] is not None: + json_load = '%s,"groupaccess": %s' % (json_load, to_native(cpmmodule.params["user_groupaccess"])) + if cpmmodule.params["user_accessserial"] is not None: + json_load = '%s,"accessserial": %s' % (json_load, to_native(cpmmodule.params["user_accessserial"])) + if cpmmodule.params["user_accessssh"] is not None: + json_load = '%s,"accessssh": %s' % (json_load, to_native(cpmmodule.params["user_accessssh"])) + if cpmmodule.params["user_accessweb"] is not None: + json_load = '%s,"accessweb": %s' % (json_load, to_native(cpmmodule.params["user_accessweb"])) + if cpmmodule.params["user_accessoutbound"] is not None: + json_load = '%s,"accessoutbound": %s' % (json_load, to_native(cpmmodule.params["user_accessoutbound"])) + if cpmmodule.params["user_accessapi"] is not None: + json_load = '%s,"accessapi": %s' % (json_load, to_native(cpmmodule.params["user_accessapi"])) + if cpmmodule.params["user_accessmonitor"] is not None: + json_load = '%s,"accessmonitor": %s' % (json_load, to_native(cpmmodule.params["user_accessmonitor"])) + if cpmmodule.params["user_callbackphone"] is not None: + json_load = '%s,"callbackphone": "%s"' % (json_load, to_native(cpmmodule.params["user_callbackphone"])) + + json_load = '%s}}' % (json_load) + + return json_load + + +def run_module(): + + module_args = dict( + cpm_action=dict(choices=['getuser', 'adduser', 'edituser', 'deleteuser'], required=True), + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True, no_log=False), + cpm_password=dict(type='str', required=True, no_log=True), + user_name=dict(type='str', required=True), + user_pass=dict(type='str', required=False, default=None, no_log=True), + user_accesslevel=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3]), + user_accessssh=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessserial=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessweb=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessapi=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessmonitor=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessoutbound=dict(type='int', required=False, default=None, choices=[0, 1]), + user_portaccess=dict(type='str', required=False, default=None), + user_plugaccess=dict(type='str', required=False, default=None), + user_groupaccess=dict(type='str', required=False, default=None), + user_callbackphone=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) + + if module.check_mode: + return result + + 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://" + + payload = None + if (module.params['cpm_action'] == 'getuser'): + fullurl = ("%s%s/api/v2/config/users?username=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['user_name']))) + method = 'GET' + elif (module.params['cpm_action'] == 'adduser'): + if module.params["user_pass"] is None or (len(module.params["user_pass"]) == 0): + module.fail_json(msg='user_pass not defined.', **result) + + payload = assemble_json(module) + fullurl = ("%s%s/api/v2/config/users" % (protocol, to_native(module.params['cpm_url']))) + method = 'POST' + elif (module.params['cpm_action'] == 'edituser'): + payload = assemble_json(module) + fullurl = ("%s%s/api/v2/config/users" % (protocol, to_native(module.params['cpm_url']))) + method = 'PUT' + elif (module.params['cpm_action'] == 'deleteuser'): + fullurl = ("%s%s/api/v2/config/users?username=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['user_name']))) + method = 'DELETE' + + 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}) + if (method != 'GET'): + result['changed'] = True + + except HTTPError as e: + fail_json = dict(msg='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='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='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='Error connecting to for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = to_text(response.read()) + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() -- cgit v1.2.3