Migrated to wti.remote

This commit is contained in:
Ansible Core Team 2020-03-09 09:40:37 +00:00 committed by Matt Martz
parent cc2feea51b
commit c788ee69d9
8 changed files with 0 additions and 1725 deletions

View file

@ -1,261 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2018 Red Hat Inc.
# Copyright (C) 2018 Western Telematic Inc. <kenp@wti.com>
#
# 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.
required: true
choices: [ "getplugconfig", "setplugconfig" ]
cpm_url:
description:
- This is the URL of the WTI device to send the module.
required: true
cpm_username:
description:
- This is the Username of the WTI device to send the module.
cpm_password:
description:
- This is the Password of the WTI device to send the module.
use_https:
description:
- Designates to use an https connection or http connection.
required: false
type: bool
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.
required: false
type: bool
default: true
use_proxy:
description: Flag to control if the lookup will observe HTTP proxy environment variables when present.
required: false
type: bool
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.
required: true
plug_name:
description:
- The new name of the Plug.
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'.
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.
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.
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()

View file

@ -1,226 +0,0 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2018 Red Hat Inc.
# Copyright (C) 2018 Western Telematic Inc. <kenp@wti.com>
#
# 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.
required: true
choices: [ "getplugcontrol", "setplugcontrol" ]
cpm_url:
description:
- This is the URL of the WTI device to send the module.
required: true
cpm_username:
description:
- This is the Username of the WTI device to send the module.
cpm_password:
description:
- This is the Password of the WTI device to send the module.
use_https:
description:
- Designates to use an https connection or http connection.
required: false
type: bool
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.
required: false
type: bool
default: true
use_proxy:
description: Flag to control if the lookup will observe HTTP proxy environment variables when present.
required: false
type: bool
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.
required: true
plug_state:
description:
- This is what action to take on the plug.
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()

View file

@ -1,345 +0,0 @@
#!/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.
required: true
cpm_username:
description:
- This is the Username of the WTI device to send the module.
required: true
cpm_password:
description:
- This is the Password of the WTI device to send the module.
required: true
use_https:
description:
- Designates to use an https connection or http connection.
required: false
type: bool
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.
required: false
type: bool
default: true
use_proxy:
description: Flag to control if the lookup will observe HTTP proxy environment variables when present.
required: false
type: bool
default: false
port:
description:
- This is the port number that is getting the action performed on.
required: true
type: int
portname:
description:
- This is the Name of the Port that is displayed.
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
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.
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.
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.
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.
required: false
choices: [ 0, 1, 2, 3, 4 ]
cmd:
description:
- This is the Admin Mode to assign to the port, 0=Deny, 1=Permit.
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
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.
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
required: false
break_allow:
description:
- This is if the break character is allowed to be passed through the port, 0=Off, 1=On
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
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()

View file

@ -1,218 +0,0 @@
#!/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.
required: true
cpm_username:
description:
- This is the Username of the WTI device to send the module.
required: true
cpm_password:
description:
- This is the Password of the WTI device to send the module.
required: true
use_https:
description:
- Designates to use an https connection or http connection.
required: false
type: bool
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.
required: false
type: bool
default: true
use_proxy:
description: Flag to control if the lookup will observe HTTP proxy environment variables when present.
required: false
type: bool
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.
required: true
type: list
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=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://"
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()

View file

@ -1,338 +0,0 @@
#!/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
choices: [ "getuser", "adduser", "edituser", "deleteuser" ]
cpm_url:
description:
- This is the URL of the WTI device to send the module.
required: true
cpm_username:
description:
- This is the Basic Authentication Username of the WTI device to send the module.
required: true
cpm_password:
description:
- This is the Basic Authentication Password of the WTI device to send the module.
required: true
use_https:
description:
- Designates to use an https connection or http connection.
required: false
type: bool
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.
required: false
type: bool
default: true
use_proxy:
description: Flag to control if the lookup will observe HTTP proxy environment variables when present.
required: false
type: bool
default: false
user_name:
description:
- This is the User Name that needs to be create/modified/deleted
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
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
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
required: false
choices: [ 0, 1 ]
user_accessserial:
description:
- If the user has access to the WTI device via Serial ports
- 0 No , 1 Yes
required: false
choices: [ 0, 1 ]
user_accessweb:
description:
- If the user has access to the WTI device via Web
- 0 No , 1 Yes
required: false
choices: [ 0, 1 ]
user_accessapi:
description:
- If the user has access to the WTI device via RESTful APIs
- 0 No , 1 Yes
required: false
choices: [ 0, 1 ]
user_accessmonitor:
description:
- If the user has ability to monitor connection sessions
- 0 No , 1 Yes
required: false
choices: [ 0, 1 ]
user_accessoutbound:
description:
- If the user has ability to initiate Outbound connection
- 0 No , 1 Yes
required: false
choices: [ 0, 1 ]
user_portaccess:
description:
- If AccessLevel is lower than Administrator, which ports the user has access
required: false
user_plugaccess:
description:
- If AccessLevel is lower than Administrator, which plugs the user has access
required: false
user_groupaccess:
description:
- If AccessLevel is lower than Administrator, which Groups the user has access
required: false
user_callbackphone:
description:
- This is the Call Back phone number used for POTS modem connections
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),
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()

View file

@ -1,165 +0,0 @@
# (c) 2018, Western Telematic Inc. <kenp@wti.com>
# (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.
required: true
choices: [ "getpower", "getcurrent" ]
cpm_url:
description:
- This is the URL of the WTI device to send the module.
required: true
cpm_username:
description:
- This is the Username of the WTI device to send the module.
cpm_password:
description:
- This is the Password of the WTI device to send the module.
use_https:
description:
- Designates to use an https connection or http connection.
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.
required: false
type: bool
default: true
use_proxy:
description: Flag to control if the lookup will observe HTTP proxy environment variables when present.
type: boolean
default: True
startdate:
description:
- Start date of the range to look for power data
required: false
enddate:
description:
- End date of the range to look for power data
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

View file

@ -1,160 +0,0 @@
# (c) 2018, Western Telematic Inc. <kenp@wti.com>
# (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.
required: true
choices: [ "temperature", "firmware", "status", "alarms" ]
cpm_url:
description:
- This is the URL of the WTI device to send the module.
required: true
cpm_username:
description:
- This is the Basic Authentication Username of the WTI device to send the module.
required: true
cpm_password:
description:
- This is the Basic Authentication Password of the WTI device to send the module.
required: true
use_https:
description:
- Designates to use an https connection or http connection.
required: false
type: bool
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.
required: false
type: bool
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

View file

@ -179,18 +179,6 @@ lib/ansible/modules/packaging/os/yum_repository.py validate-modules:doc-missing-
lib/ansible/modules/packaging/os/yum_repository.py validate-modules:parameter-list-no-elements lib/ansible/modules/packaging/os/yum_repository.py validate-modules:parameter-list-no-elements
lib/ansible/modules/packaging/os/yum_repository.py validate-modules:parameter-type-not-in-doc lib/ansible/modules/packaging/os/yum_repository.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/packaging/os/yum_repository.py validate-modules:undocumented-parameter lib/ansible/modules/packaging/os/yum_repository.py validate-modules:undocumented-parameter
lib/ansible/modules/remote_management/cpm/cpm_plugconfig.py validate-modules:doc-missing-type
lib/ansible/modules/remote_management/cpm/cpm_plugconfig.py validate-modules:doc-required-mismatch
lib/ansible/modules/remote_management/cpm/cpm_plugconfig.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/remote_management/cpm/cpm_plugcontrol.py validate-modules:doc-missing-type
lib/ansible/modules/remote_management/cpm/cpm_plugcontrol.py validate-modules:doc-required-mismatch
lib/ansible/modules/remote_management/cpm/cpm_plugcontrol.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/remote_management/cpm/cpm_serial_port_config.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/remote_management/cpm/cpm_serial_port_info.py validate-modules:doc-required-mismatch
lib/ansible/modules/remote_management/cpm/cpm_serial_port_info.py validate-modules:parameter-list-no-elements
lib/ansible/modules/remote_management/cpm/cpm_serial_port_info.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/remote_management/cpm/cpm_user.py validate-modules:doc-missing-type
lib/ansible/modules/remote_management/cpm/cpm_user.py validate-modules:parameter-type-not-in-doc
lib/ansible/modules/source_control/git.py pylint:blacklisted-name lib/ansible/modules/source_control/git.py pylint:blacklisted-name
lib/ansible/modules/source_control/git.py use-argspec-type-path lib/ansible/modules/source_control/git.py use-argspec-type-path
lib/ansible/modules/source_control/git.py validate-modules:doc-missing-type lib/ansible/modules/source_control/git.py validate-modules:doc-missing-type