Init: mediaserver

This commit is contained in:
2023-02-08 12:13:28 +01:00
parent 848bc9739c
commit f7c23d4ba9
31914 changed files with 6175775 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
===================================
WTI Collection Release Notes
===================================
.. contents:: Topics
v1.0.4
======
Major Changes
-------------
Minor Changes
-------------
Sanity test changes as requested by RedHat
Bugfixes
--------
Modified syslog and snmp config to match the JSON schema of new WTI devices
Documentation Changes
---------------------
Release Summary
----------------
New Modules
-----------

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,37 @@
{
"collection_info": {
"namespace": "wti",
"name": "remote",
"version": "1.0.4",
"authors": [
"Ken Partridge <kenp@wti.com> (@wtinetworkgear)"
],
"readme": "README.md",
"tags": [
"wti",
"remote",
"oob",
"pdu",
"management",
"control"
],
"description": "Modules for interacting with WTI remote OOB and PDU devices",
"license": [
"GPL-2.0-or-later"
],
"license_file": null,
"dependencies": {},
"repository": "https://github.com/wtinetworkgear/wti-collection",
"documentation": "https://github.com/wtinetworkgear/wti-collection/tree/master/wti/remote/docs",
"homepage": "https://www.wti.com",
"issues": "https://github.com/wtinetworkgear/wti-collection/issues"
},
"file_manifest_file": {
"name": "FILES.json",
"ftype": "file",
"chksum_type": "sha256",
"chksum_sha256": "e48169c1bb6909b4ea785ae871ae3a2fe9b93a38e49905f51d42f4da4a41786b",
"format": 1
},
"format": 1
}

View File

@@ -0,0 +1,55 @@
WTI Ansible Collection
=========
This [Ansible](https://www.ansible.com/) collection provides a set of platform dependent configuration
management modules specifically designed for [WTI OOB and PDU devices](https://wti.com/) .
Requirements
------------
* Python 3.5+
* Ansible 2.9.0 or later
* Supported WTI firmware (DSM/CPM v6.58+, VMR 2.15+)
* Configuration command needs a user with Administrator privileges
Installation
-------
Through Galaxy:
```
ansible-galaxy collection install wti.remote
```
Inventory Variables
--------------
The common variables that should be defined in your inventory for your WTI host are:
* `cpm_url`: IP address or name of device.
* `cpm_username`: Username for device in `plaintext` format
* `cpm_password`: Password for device in `plaintext` format
* `use_https`: Set `True` or `False` depending on if Ansible should use a secure https connection
* `validate_certs`: Set `True` or `False` depending on if Ansible should attempt to validate certificates
* `use_proxy`: Set `True` or `False` depending if Ansible should bypass environment proxies to connect to the WTI device
Contribution
-------
At WTI we're dedicated to ensuring the quality of our products, if you find any
issues at all please open an issue on our [Github](https://github.com/wtinetworkgear/wti-collection) and we'll be sure to respond promptly!
Or you can always email us directly at support@wti.com
License
-------
Apache-2.0
Author Information
------------------
- Ken Partridge (@wtinetworkgear)

View File

@@ -0,0 +1,3 @@
dependencies:
python: requirements-wti.txt
version: 1

View File

@@ -0,0 +1,35 @@
requires_ansible: '>=2.9.10'
action_groups:
cpm:
- cpm_alarm_info
- cpm_config_backup
- cpm_config_restore
- cpm_current_info
- cpm_firmware_info
- cpm_firmware_update
- cpm_hostname_config
- cpm_hostname_info
- cpm_interface_config
- cpm_interface_info
- cpm_iptables_config
- cpm_iptables_info
- cpm_plugconfig
- cpm_plugcontrol
- cpm_power_info
- cpm_serial_port_action_info
- cpm_serial_port_action_set
- cpm_serial_port_config
- cpm_serial_port_info
- cpm_snmp_config
- cpm_snmp_info
- cpm_status_info
- cpm_syslog_client_config
- cpm_syslog_client_info
- cpm_syslog_server_info
- cpm_syslog_server_config
- cpm_temp_info
- cpm_time_config
- cpm_time_info
- cpm_user

View File

@@ -0,0 +1,26 @@
# ansible-playbook ./cpm_config_backup.yml -e ansible_hosts=nameofhost
- name: Get Device Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=False
when: use_https is undefined
- set_fact: validate_certs=False
when: validate_certs is undefined
- name: run Get Network Interface
cpm_config_backup:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,27 @@
# ansible-playbook ./cpm_config_restore.yml -e ansible_hosts=nameofhost
- name: Set Device Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=False
when: use_https is undefined
- set_fact: validate_certs=False
when: validate_certs is undefined
- name: run Set Device Parameters
cpm_config_restore:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
cpm_filename: "wti-192-10-10-239-2020-02-13T16-17-22-xml"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,29 @@
# ansible-playbook ./firmware_upgrade.yml
- name: Upgrade WTI Device
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=False
when: use_https is undefined
- set_fact: validate_certs=False
when: validate_certs is undefined
- name: upgrade WTI device checking online for new version
cpm_firmware_update:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
cpm_path: "/tmp/"
# when cpm_file is missing, the playbook will look online for the latest version
# cpm_file: "uimage_3352_tsm_arm.md5"
# cpm_file: "uimage_3352_128512_vmr_v2.15.md5"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,28 @@
# ansible-playbook ./hostname_config.yml -e ansible_hosts=youransibledefinedhostnames
- name: Set Hostname (Site ID), Location, Asset Tag parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- cpm_hostname_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
hostname: "newhostname"
location: "newlocation"
assettag: "newassettag"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,25 @@
# ansible-playbook ./hostname_info.yml -e ansible_hosts=youransibledefinedhostnames
- name: Get Hostname (Site ID), Location, Asset Tag parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- cpm_hostname_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,31 @@
# ansible-playbook ./interface_config.yml -e ansible_hosts=nameofhost
- name: Set Network Interface parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- cpm_interface_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
interface: "eth1"
ipv4netmask: "255.255.255.0"
ipv4gateway: "192.168.0.2"
ipv4address: "192.168.0.16"
negotiation: 0
ipv4dhcpenable: 0
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,26 @@
# ansible-playbook ./interface_info.yml -e ansible_hosts=nameofhost
- name: Get Network Interface parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- cpm_interface_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
interface: "eth0"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,35 @@
# ansible-playbook ./iptables_config.yml -e ansible_hosts=nameofhost
- name: Set Network IPTABLES parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- cpm_iptables_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
protocol: 0
index:
- 1
- 2
- 48
command:
- "iptables the passed in command 2.."
- "iptables the passed in command 4.."
- "iptables the passed in command 48."
clear: 0
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,25 @@
# ansible-playbook ./iptables_info.yml -e ansible_hosts=nameofhost
- name: Get Network IPTABLES Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- cpm_iptables_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,32 @@
# ansible-playbook ./plug_config.yml -e ansible_hosts=nameofhost
- name: Set Plug Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Set Plug Parameters
cpm_plugconfig:
cpm_action: "setplugconfig"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
plug_id: "2" # plug 2 is being changed
plug_name: "plugname2"
plug_bootdelay: 1
plug_default: 0
plug_bootpriority: 99
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout }}"

View File

@@ -0,0 +1,28 @@
# ansible-playbook ./plug_info.yml -e ansible_hosts=nameofhost
- name: Get Plug Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Get Plug Parameters of plug 1
cpm_plugconfig:
cpm_action: "getplugconfig"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
plug_id: "1"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,30 @@
# ansible-playbook ./plug_control.yml -e ansible_hosts=nameofhost
- name: Control Plug State
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: Control the plug state
cpm_plugcontrol:
cpm_action: "setplugcontrol"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
plug_id: "2" # plug 2 is being changed
plug_state: "boot"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout }}"

View File

@@ -0,0 +1,28 @@
# ansible-playbook ./plug_control_info.yml -e ansible_hosts=nameofhost
- name: Get Plug Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Get Plug status of plug 1
cpm_plugcontrol:
cpm_action: "getplugcontrol"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
plug_id: "1"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,27 @@
# ansible-playbook ./serial_port_info.yml -e ansible_hosts=nameofhost
- name: Get Serial Port Connection/Disconnection state
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Get Serial Port Connection status of Ports 1, 2 and 3
cpm_serial_port_action_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
port: "1,2,3"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,29 @@
# ansible-playbook ./serial_ports_action_set.yml -e ansible_hosts=nameofhost
- name: Set Serial Port Connection/Disconnection state
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=False
when: validate_certs is undefined
- name: run Connect Serial Port 4 and 5 command
cpm_serial_port_action_set:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
port: 4
portremote: 5
action: 1
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,39 @@
# ansible-playbook ./serial_ports_config.yml -e ansible_hosts=nameofhost
- name: Set Serial Port Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Set Port Parameters of Port 4
cpm_serial_port_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
port: 4
baud: 4
portname: "Sam4"
handshake: 2
stopbits: 1
parity: 0
mode: 1
cmd: 0
seq: 1
tout: 1
echo: 0
break_allow: True
logoff: "^W"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,27 @@
# ansible-playbook ./serial_ports_info.yml -e ansible_hosts=nameofhost
- name: Get Serial Port Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Get Port Parameters of Ports 1, 2 and 3
cpm_serial_port_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
port: "1,2,3"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,54 @@
# ansible-playbook ./snmp_config.yml -e ansible_hosts=nameofhost
- name: Set Network SNMP Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Set interface parameters
cpm_snmp_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
interface: "eth0"
protocol: 0
clear: 0
enable: 0
readonly: 0
version: 2
index:
- 2
- 4
username:
- "username1b"
- "username3a"
authpass:
- "xxxxx1abc"
- "authpass3a"
privpass:
- "privpass2a"
- "privpass3a"
authpriv:
- 1
- 0
authproto:
- 0
- 0
privproto:
- 0
- 0
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,29 @@
# ansible-playbook ./snmp_info.yml -e ansible_hosts=nameofhost
- name: Get Network SNMP Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- set_fact: ansible_interface="eth0"
when: ansible_interface is undefined
- name: Run Get SNMP parameters
cpm_snmp_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
interface: "{{ansible_interface}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,25 @@
# ansible-playbook ./alarm_info.yml -e ansible_hosts=yourhostname
- name: Get Alarm information from WTI device
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- wti.remote.cpm_alarm_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,27 @@
# ansible-playbook ./current_info.yml -e ansible_hosts=yourhostname
- name: Get Current information from WTI device
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- wti.remote.cpm_current_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
cpm_startdate: "02-02-2020"
cpm_enddate: "02-28-2020"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,25 @@
# ansible-playbook ./firmware_info.yml -e ansible_hosts=yourhostname
- name: Get Firmware information from WTI device
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- wti.remote.cpm_firmware_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,27 @@
# ansible-playbook ./temp_info.yml -e ansible_hosts=yourhostname
- name: Get Power information from WTI device
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- wti.remote.cpm_power_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
cpm_startdate: "02-02-2020"
cpm_enddate: "02-28-2020"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,25 @@
# ansible-playbook ./status_info.yml -e ansible_hosts=yourhostname
- name: Get Status information from WTI device
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- wti.remote.cpm_status_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,25 @@
# ansible-playbook ./temp_info.yml -e ansible_hosts=yourhostname
- name: Get Temperature information from WTI device
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- wti.remote.cpm_temp_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,43 @@
# ansible-playbook ./syslog_client_config.yml -e ansible_hosts=nameofhost
- name: Set Network SYSLOG Client Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Set interface parameters
cpm_syslog_client_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
protocol: 0
clear: 1
index:
- 1
- 3
address:
- "11.22.33.44"
- "55.66.77.88"
port:
- 555
- 557
transport:
- 1
- 0
secure:
- 0
- 1
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,30 @@
# ansible-playbook ./syslog_client_info.yml -e ansible_hosts=nameofhost
- name: Get Network SYSLOG Client Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- set_fact: ansible_interface="eth0"
when: ansible_interface is undefined
- name: Run Get SYSLOG Server parameters
cpm_syslog_client_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
interface: "{{ansible_interface}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,40 @@
# ansible-playbook ./syslog_server_config.yml -e ansible_hosts=nameofhost
- name: Set Network SNMP Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Set interface parameters
cpm_syslog_server_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
interface: "eth0"
protocol: 0
clear: 1
enable: 1
port: 555
transport: 1
secure: 0
index:
- 1
- 3
address:
- "11.22.33.44"
- "55.66.77.88"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,30 @@
# ansible-playbook ./syslog_server_info.yml -e ansible_hosts=nameofhost
- name: Get Network SYSLOG Server Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- set_fact: ansible_interface="eth0"
when: ansible_interface is undefined
- name: Run Get SYSLOG Server parameters
cpm_syslog_server_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
interface: "{{ansible_interface}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,29 @@
# ansible-playbook ./time_config.yml -e ansible_hosts=nameofhost
- name: Set Time Date parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=False
when: use_https is undefined
- set_fact: validate_certs=False
when: validate_certs is undefined
- cpm_time_config:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
timezone: 5
ntpenable: 1
ipv4address: "time1.google.com,time2.google.com"
timeout: 4
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,25 @@
# ansible-playbook ./time_info.yml -e ansible_hosts=yourhostname
- name: Get Time/Date and NTP parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- cpm_time_info:
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,45 @@
# ansible-playbook ./user_add.yml -e ansible_hosts=nameofhost
- name: Add New User
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
vars_prompt:
- name: "user_name"
prompt: "Enter Username"
private: no
- name: "user_pass"
prompt: "Enter Password"
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Add New User
cpm_user:
cpm_action: "adduser"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
user_name: "{{user_name}}" # pass as -e user_name=sammy on the commandline
user_pass: "{{user_pass}}"
user_accesslevel: 1
user_accessserial: 0
user_accessapi: 1
user_accessweb: 0
user_accessoutbound: 1
user_accessssh: 1
user_portaccess: "10001110"
user_plugaccess: "11110000"
user_callbackphone: "9495551212"
use_https: "{{use_https}}"
validate_certs: "{{validate_certs}}"
register: output
- name: dump JSON output
debug:
msg: "{{ output.data }}"

View File

@@ -0,0 +1,33 @@
# ansible-playbook ./user_delete.yml -e ansible_hosts=nameofhost
- name: Delete Exiting User
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
vars_prompt:
- name: "user_name"
prompt: "Enter Username"
private: no
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Delete Exiting User
cpm_user:
cpm_action: "deleteuser"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
user_name: "{{user_name}}" # pass as -e user_name=sammy on the commandline
use_https: "{{use_https}}"
validate_certs: false
register: output
- name: dump JSON output
debug:
msg: "{{ output.data }}"

View File

@@ -0,0 +1,37 @@
# ansible-playbook ./user_edit.yml -e ansible_hosts=nameofhost
- name: Edit Exiting User
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
vars_prompt:
- name: "user_name"
prompt: "Enter Username"
private: no
- name: "user_pass"
prompt: "Enter Password"
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: Run Edit Existing User
cpm_user:
cpm_action: "edituser"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
user_name: "{{user_name}}" # pass as -e user_name=sammy on the commandline
user_pass: "{{user_pass}}" # pass as -e user_pass=sammy on the commandline
user_accesslevel: 3
use_https: "{{use_https}}"
validate_certs: false
register: testout
- name: dump test output
debug:
msg: "{{ testout['data'] }}"

View File

@@ -0,0 +1,33 @@
# ansible-playbook ./user_get.yml -e ansible_hosts=nameofhost
- name: Get User Parameters
hosts: "{{ansible_hosts}}" # pass as -e ansible_hosts=wti_demo on the commandline
collections:
- wti.remote
connection: local
gather_facts: False
vars_prompt:
- name: "user_name"
prompt: "Enter Username"
private: no
tasks:
- set_fact: use_https=True
when: use_https is undefined
- set_fact: validate_certs=True
when: validate_certs is undefined
- name: run Get User Parameters
cpm_user:
cpm_action: "getuser"
cpm_url: "{{ansible_host}}"
cpm_username: "{{ansible_user}}"
cpm_password: "{{ansible_pw}}"
user_name: "{{user_name}}" # pass as -e user_name=sammy on the commandline
use_https: "{{use_https}}"
validate_certs: false
register: output
- name: dump JSON output
debug:
msg: "{{ output.data }}"

View File

@@ -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.0"
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()

View File

@@ -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.0"
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()

View File

@@ -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.0"
author: "Western Telematic Inc. (@wtinetworkgear)"
short_description: Send operational parameters to WTI OOB and PDU devices
description:
- "Send operational parameters to 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()

View File

@@ -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.0"
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()

View File

@@ -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.0"
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()

View File

@@ -0,0 +1,365 @@
#!/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 upgeade the firmware 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_firmware_update
version_added: "2.9.0"
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
type: str
cpm_username:
description:
- This is the Username of the WTI device to send the module.
required: true
type: str
cpm_password:
description:
- This is the Password of the WTI device to send the module.
required: true
type: str
cpm_path:
description:
- This is the directory path to store the WTI device configuration file.
required: false
type: str
default: "/tmp/"
cpm_file:
description:
- If a file is defined, this file will be used to update the WTI device.
required: false
type: str
use_force:
description:
- If set to True, the upgrade will happen even if the device doesnt need it.
required: false
type: bool
default: false
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
family:
description:
- Force the download to both either Console (1) or Power (0)
required: false
type: int
default: 1
choices: [ 0, 1 ]
removefileonexit:
description:
- After an upgrade, remove the upgrade OS image
required: false
type: int
default: 1
choices: [ 0, 1 ]
notes:
- Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.
"""
EXAMPLES = """
# Upgrade the firmware of a WTI device
- name: Upgrade the firmware of a WTI device
cpm_firmware_update:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
# Upgrade the firmware of a WTI device and keep the download OS image after exit
- name: Upgrade the firmware of a WTI device and keep the download OS image after exit
cpm_firmware_update:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
removefileonexit: "0"
"""
RETURN = """
data:
description: The output XML configuration of the WTI device being updated
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 os
import json
import tempfile
import traceback
import shutil
import requests
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
from ansible.module_utils.urls import fetch_url, url_argument_spec
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_file=dict(type='str', default=None),
family=dict(type='int', default=1, choices=[0, 1]),
removefileonexit=dict(type='int', default=1, choices=[0, 1]),
use_force=dict(type='bool', default=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=''
)
family = None
fips = None
online_file_location = None
usersuppliedfilename = None
forceupgrade = False
localfilefamily = -1
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
if module.params['cpm_file'] is not None:
usersuppliedfilename = ("%s%s" % (to_native(module.params['cpm_path']), to_native(module.params['cpm_file'])))
if module.params['use_force'] is True:
forceupgrade = True
# if a local file was defined lets see what family it is: Console or Power
if (usersuppliedfilename is not None):
try:
ifilesize = os.path.getsize(usersuppliedfilename)
file = open(usersuppliedfilename, 'rb')
file.seek(ifilesize - 20)
fileread = file.read()
if (fileread.find(b"TSM") >= 0):
localfilefamily = 1
elif (fileread.find(b"VMR") >= 0):
localfilefamily = 0
file.close()
# print("User Supplied file [%s] is a %s type." %(usersuppliedfilename, ("Console" if localfilefamily == 1 else "Power")))
except Exception as e:
fail_json = dict(msg='FILE: User Supplied file {0} does not exist : {1}'.format(usersuppliedfilename, to_native(e)), changed=False)
module.fail_json(**fail_json)
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://"
# 1. Get the Version and fips support of the WTI device
fullurl = ("%s%s/api/v2/status/firmware" % (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'] = json.loads(response.read())
statuscode = result['data']["status"]["code"]
local_release_version = result['data']["config"]["firmware"]
try:
family = int(result['data']["config"]["family"])
except Exception as e:
family = 1
try:
fips = int(result['data']["config"]["fips"])
if (fips == 0):
fips = 2 # get me the no fips or merged code
except Exception as ex:
fips = 1
# print("Device reports Version: %s, Family: %s\n" % (local_release_version, ("Console" if family == 1 else "Power")))
if (localfilefamily != -1):
if (family != localfilefamily):
fail_json = dict(msg='FAMILY MISMATCH: Your local file is a: %s type, the device is a %s type'
% (("Console" if localfilefamily == 1 else "Power"), ("Console" if family == 1 else "Power")), changed=False)
module.fail_json(**fail_json)
# 2. Go online and find the latest version of the os image for this device family
if (localfilefamily == -1):
fullurl = ("https://my.wti.com/update/version.aspx?fam=%s" % (family))
if (fips is not None):
fullurl = ("%s&fipsonly=%d" % (fullurl, fips))
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())
remote_release_version = result['data']["config"]["firmware"]
if ((float(local_release_version) < 6.58) & (family == 1)) | ((float(local_release_version) < 2.15) & (family == 0)):
fail_json = dict(msg='ERROR: WTI Device does not support remote upgrade', changed=False)
module.fail_json(**fail_json)
statuscode = result['data']['status']['code']
else:
remote_release_version = 0
if (int(statuscode) == 0):
local_filename = None
if ((float(local_release_version) < float(remote_release_version)) or (forceupgrade == 1)) or (localfilefamily >= 0):
if (module.check_mode is False):
if (localfilefamily == -1):
online_file_location = result['data']["config"]["imageurl"]
local_filename = online_file_location[online_file_location.rfind("/") + 1:]
local_filename = tempfile.gettempdir() + "/" + local_filename
response = requests.get(online_file_location, stream=True)
handle = open(local_filename, "wb")
for chunk in response.iter_content(chunk_size=512):
if chunk: # filter out keep-alive new chunks
handle.write(chunk)
handle.close()
else:
if (family == localfilefamily):
local_filename = usersuppliedfilename
else:
print("FAMILY MISMATCH: Your local file is a %s type, and the device is a %s type\n\n"
% (("Console" if localfilefamily == 1 else "Power"), ("Console" if family == 1 else "Power")))
exit(3)
# SEND the file to the WTI device
# 3. upload new os image to WTI device
fullurl = ("%s%s/cgi-bin/getfile" % (protocol, to_native(module.params['cpm_url'])))
files = {'file': ('name.binary', open(local_filename, 'rb'), 'application/octet-stream')}
try:
response = requests.post(fullurl, files=files, auth=(to_native(module.params['cpm_username']),
to_native(module.params['cpm_password'])), verify=(module.params['validate_certs']), stream=True)
result['data'] = response.json()
if (response.status_code == 200):
if (int(result['data']['status']['code']) == 0):
result['changed'] = True
else:
fail_json = dict(msg='FAIL: Upgrade Failed for {0}'.format(fullurl), changed=False)
module.fail_json(**fail_json)
except requests.exceptions.RequestException as e: # This is the correct syntax
fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False)
module.fail_json(**fail_json)
# only remove if the file was downloaded
if (localfilefamily == -1):
if (int(module.params['removefileonexit']) == 1):
os.remove(local_filename)
else:
result['data'] = "{ \"filelength\": \"0\", \"status\": { \"code\": \"1\", \"text\": \"device up to date\" } }"
else:
result['data'] = "{ \"filelength\": \"0\", \"status\": { \"code\": \"2\", \"text\": \"device bad family code: %s\" } }" % (family)
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,284 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2019 Red Hat Inc.
# Copyright (C) 2021 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 hostname 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_hostname_config
version_added: "2.11.0"
author:
- "Western Telematic Inc. (@wtinetworkgear)"
short_description: Set Hostname (Site ID), Location, Asset Tag parameters in WTI OOB and PDU devices.
description:
- "Set Hostname (Site ID), Location, Asset Tag 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
hostname:
description:
- This is the Hostname (Site-ID) tag to be set for the WTI OOB and PDU device.
type: str
required: false
location:
description:
- This is the Location tag to be set for the WTI OOB and PDU device.
type: str
required: false
assettag:
description:
- This is the Asset Tag to be set for the WTI OOB and PDU device.
type: str
required: false
notes:
- Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.
"""
EXAMPLES = """
# Set Hostname, Location and Site-ID variables of a WTI device
- name: Set known fixed hostname variables of a WTI device
cpm_time_config:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
hostname: "myhostname"
location: "Irvine"
assettag: "irvine92395"
# Set the Hostname variable of a WTI device
- name: Set the Hostname of a WTI device
cpm_time_config:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
hostname: "myhostname"
"""
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: "2021-08-17T21:33:50+00:00"
hostname:
description: Current Hostname (Site-ID) of the WTI device after module execution.
returned: success
type: str
sample: "myhostname"
location:
description: Current Location of the WTI device after module execution.
returned: success
type: int
sample: "Irvine"
assettag:
description: Current Asset Tag of the WTI device after module execution.
returned: success
type: int
sample: "irvine92395"
"""
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 = ""
localhostname = locallocation = localassettag = None
if cpmmodule.params["hostname"] is not None:
if (existing["unitid"]["hostname"] != to_native(cpmmodule.params["hostname"])):
total_change = (total_change | 1)
localhostname = to_native(cpmmodule.params["hostname"])
if cpmmodule.params["location"] is not None:
if (existing["unitid"]["location"] != to_native(cpmmodule.params["location"])):
total_change = (total_change | 2)
locallocation = to_native(cpmmodule.params["location"])
if cpmmodule.params["assettag"] is not None:
if (existing["unitid"]["assettag"] != to_native(cpmmodule.params["assettag"])):
total_change = (total_change | 4)
localassettag = to_native(cpmmodule.params["assettag"])
if (total_change > 0):
protocol = protocolchanged = 0
ietfstring = ""
if (localhostname is not None):
ietfstring = '%s"hostname": "%s"' % (ietfstring, localhostname)
if (locallocation is not None):
if (len(ietfstring) > 0):
ietfstring = '%s,' % (ietfstring)
ietfstring = '%s"location": "%s"' % (ietfstring, locallocation)
if (localassettag is not None):
if (len(ietfstring) > 0):
ietfstring = '%s,' % (ietfstring)
ietfstring = '%s"assettag": "%s"' % (ietfstring, localassettag)
json_load = '{"unitid": {'
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),
hostname=dict(type='str', required=False, default=None),
location=dict(type='str', required=False, default=None),
assettag=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/hostname" % (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/hostname" % (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

@@ -0,0 +1,187 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2019 Red Hat Inc.
# Copyright (C) 2021 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 hostname 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_hostname_info
version_added: "2.11.0"
author:
- "Western Telematic Inc. (@wtinetworkgear)"
short_description: Get Hostname (Site ID), Location, Asset Tag parameters in WTI OOB and PDU devices
description:
- "Get Hostname (Site ID), Location, Asset Tag 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 Hostname parameters for a WTI device
cpm_hostname_info:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
- name: Get the Hostname parameters for a WTI device
cpm_hostname_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:
timestamp:
description: Current timestamp of the WTI device after module execution.
returned: success
type: str
sample: "2021-08-17T21:33:50+00:00"
hostname:
description: Current Hostname (Site-ID) of the WTI device after module execution.
returned: success
type: str
sample: "myhostname"
location:
description: Current Location of the WTI device after module execution.
returned: success
type: int
sample: "Irvine"
assettag:
description: Current Asset Tag of the WTI device after module execution.
returned: success
type: int
sample: "irvine92395"
"""
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/hostname" % (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()

View File

@@ -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.0"
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()

View File

@@ -0,0 +1,211 @@
#!/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.0"
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
face:
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
elements: raw
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.
choices:
- eth0
- eth1
- ppp0
- qmimux0
required: false
type: str
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),
face=dict(type='list', elements='raw', default=None),
interface=dict(
required=False,
type="str",
choices=["eth0", "eth1", "ppp0", "qmimux0"],
),
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()

View File

@@ -0,0 +1,297 @@
#!/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.0"
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
elements: raw
command:
description:
- Actual iptables command to send to the WTI device.
type: list
required: true
elements: raw
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', elements='raw', required=False, default=None),
command=dict(type='list', elements='raw', 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()

View File

@@ -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.0"
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()

View File

@@ -0,0 +1,174 @@
# (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 = """
name: cpm_metering
author: "Western Telematic Inc. (@wtinetworkgear)"
version_added: "2.7.0"
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

View File

@@ -0,0 +1,272 @@
#!/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.0"
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()

View File

@@ -0,0 +1,234 @@
#!/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.0"
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()

View File

@@ -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.0"
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()

View File

@@ -0,0 +1,197 @@
#!/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 Connection status 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_action_info
version_added: "2.9.0"
author: "Western Telematic Inc. (@wtinetworkgear)"
short_description: Get Serial port connection status in WTI OOB and PDU devices
description:
- "Get Serial port connection 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: 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
elements: raw
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_action_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_action_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:
ports:
description: List of connection status for each serial port
returned: success
type: list
sample:
- port: 2
connstatus: "Free"
- port: 4
connstatus: " C-06"
"""
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', elements='raw', 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/serialportsaction?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

@@ -0,0 +1,264 @@
#!/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 Connection 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_serial_port_action_set
version_added: "2.9.0"
author: "Western Telematic Inc. (@wtinetworkgear)"
short_description: Set Serial port connection/disconnection commands in WTI OOB and PDU devices
description:
- "Set Serial port connection/disconnection commands 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
portremote:
description:
- This is the port number that is getting the action performed on.
type: int
required: false
action:
description:
- This is the baud rate to assign to the port.
- 1=Connect, 2=Disconnect
type: int
required: false
choices: [ 1, 2 ]
notes:
- Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.
"""
EXAMPLES = """
# Set Serial Port Action (Connect)
- name: Connect port 2 to port 3 of a WTI device
cpm_serial_port_action_set:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
port: "2"
portremote: "3"
action: "1"
# Set Serial port Action (Disconnect)
- name: Disconnect port 2 and 3 of a WTI device
cpm_serial_port_action_set:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
port: "2"
action: "2"
"""
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):
error_int = 0
error_json = None
json_load = None
items = len(existing_serial['ports'])
for x in range(0, items):
if (existing_serial["ports"][x]["port"] == to_native(cpmmodule.params["port"])):
json_load = '%s - match and is %s' % (json_load, existing_serial["ports"][x]["connstatus"])
if ((cpmmodule.params["action"] == 1) & (existing_serial["ports"][x]["connstatus"] != "Free")):
error_json = '{"status": {"code": "1", "text": "port %s is busy"}}' % (to_native(cpmmodule.params["port"]))
error_int = error_int | 1
if ((cpmmodule.params["action"] == 2) & (existing_serial["ports"][x]["connstatus"] == "Free")):
error_json = '{"status": {"code": "2", "text": "port is already free"}}'
error_int = error_int | 2
if (existing_serial["ports"][x]["port"] == to_native(cpmmodule.params["portremote"])):
json_load = '%s - match and is %s' % (json_load, existing_serial["ports"][x]["connstatus"])
if ((cpmmodule.params["action"] == 1) & (existing_serial["ports"][x]["connstatus"] != "Free")):
error_json = '{"status": {"code": "3", "text": "portremote %s is busy"}}' % (to_native(cpmmodule.params["portremote"]))
error_int = error_int | 4
if (error_int == 0):
json_load = '{"serialports": {"port": %s, "action": %s' % (to_native(cpmmodule.params["port"]), to_native(cpmmodule.params["action"]))
if (cpmmodule.params["portremote"] is not None):
json_load = '%s, "portremote": %s' % (json_load, to_native(cpmmodule.params["portremote"]))
json_load = '%s }}' % (json_load)
else:
json_load = None
return json_load, error_json
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),
port=dict(type='int', required=True),
portremote=dict(type='int', required=False),
action=dict(type='int', required=False, default=None, choices=[1, 2])
)
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://"
tempports = to_native(module.params['port'])
if (len(to_native(module.params['portremote']))):
tempports = '%s,%s' % (tempports, to_native(module.params['portremote']))
fullurl = ("%s%s/api/v2/config/serialportsaction?ports=%s" % (protocol, to_native(module.params['cpm_url']), to_native(tempports)))
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, payload_error = assemble_json(module, json.loads(response.read()))
if (payload_error is not None):
result['data'] = payload_error
else:
result['data'] = payload
if module.check_mode:
if payload is not None:
result['changed'] = True
else:
if payload is not None:
fullurl = ("%s%s/api/v2/config/serialportsaction" % (protocol, to_native(module.params['cpm_url'])))
result['data'] = payload
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

@@ -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.0"
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, 1=1 Stop Bit, 2=2 Stop Bit.
type: int
required: false
choices: [ 1, 2 ]
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, 1=Three Characters (before and after), 2=One Character Only, 3=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: "1"
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=[1, 2]),
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

@@ -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.0"
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
elements: raw
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', elements='raw', 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()

View File

@@ -0,0 +1,615 @@
#!/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.0"
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: true
choices:
- eth0
- eth1
- ppp0
- qmimux0
type: str
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
elements: raw
required: false
username:
description:
- Sets the User Name for SNMPv3 access (V3 only).
type: list
elements: raw
required: false
authpriv:
description:
- Configures the Authentication and Privacy features for SNMPv3 communication, 0 = Auth/NoPriv, 1 = Auth/Priv (V3 only).
type: list
elements: raw
required: false
authpass:
description:
- Sets the Authentication Password for SNMPv3 (V3 only).
type: list
elements: raw
required: false
authproto:
description:
- Which authentication protocol will be used, 0 = MD5, 1 = SHA1 (V3 only).
type: list
elements: raw
required: false
privpass:
description:
- Sets the Privacy Password for SNMPv3 (V3 only) (V3 only).
type: list
elements: raw
required: false
privproto:
description:
- Which privacy protocol will be used, 0 = DES, 1 = AES128 (V3 only).
type: list
elements: raw
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", "qmimux0"]),
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', required=False, default=None),
contact=dict(type='str', required=False, default=None),
location=dict(type='str', required=False, default=None),
rocommunity=dict(type='str', required=False, default=None, no_log=True),
rwcommunity=dict(type='str', required=False, default=None, no_log=True),
index=dict(type='list', elements='raw', required=False, default=None),
username=dict(type='list', elements='raw', required=False),
authpriv=dict(type='list', elements='raw', required=False, default=None),
authproto=dict(type='list', elements='raw', required=False, default=None),
privproto=dict(type='list', elements='raw', required=False, default=None),
authpass=dict(type='list', elements='raw', required=False, no_log=True),
privpass=dict(type='list', elements='raw', required=False, 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:
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()

View File

@@ -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.0"
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()

View File

@@ -0,0 +1,164 @@
# (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 = """
name: cpm_status
author: "Western Telematic Inc. (@wtinetworkgear)"
version_added: "2.7.0"
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

View File

@@ -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.0"
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()

View File

@@ -0,0 +1,440 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2019 Red Hat Inc.
# Copyright (C) 2021 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 SYSLOG Client 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_syslog_client_config
version_added: "2.11.0"
author:
- "Western Telematic Inc. (@wtinetworkgear)"
short_description: Set network SYSLOG Client parameters in WTI OOB and PDU devices
description:
- "Set network SYSLOG Client 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 SYSLOG entry should be applied. 0 = ipv4, 1 = ipv6.
type: int
required: false
choices: [ 0, 1 ]
clear:
description:
- Removes all the IP block entries for the protocol being defined before setting the newly defined entries.
type: int
required: false
choices: [ 0, 1 ]
index:
description:
- Index of the IP block being modified.
type: list
elements: raw
required: false
address:
description:
- Sets the IP Address of the SYSLOG server to contact.
type: list
elements: raw
required: false
port:
description:
- Defines the port number used by the SYSLOG Client (1 - 65535).
type: list
elements: raw
required: false
transport:
description:
- Defines the transfer protocol type used by the SYSLOG Client. 0=UDP, 1=TCP;
type: list
elements: raw
required: false
secure:
description:
- Defines if a secure connection is used by the SYSLOG Client (TCP Transport required).
type: list
elements: raw
required: false
notes:
- Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.
"""
EXAMPLES = """
# Sets the device SYSLOG Client Parameters
- name: Set the an SYSLOG Client 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
protocol: 0
index:
- 1
address:
- "11.22.33.44"
port:
- 555
transport:
- 1
secure:
- 0
# Sets the device SYSLOG Client Parameters
- name: Set the SYSLOG Client Parameters a WTI device
cpm_iptables_config:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
protocol: 0
index:
- 1
- 2
address:
- "11.22.33.44"
- "55.66.77.88"
port:
- 555
- 557
transport:
- 1
- 0
secure:
- 0
- 1
"""
RETURN = """
data:
description: The output JSON returned from the commands sent
returned: always
type: complex
contains:
syslogclient:
description: Current k/v pairs of interface info for the WTI device after module execution.
returned: always
type: dict
sample: {"syslogclient": {
"ietf-ipv4": {
"clients": [
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "1"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "2"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "3"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "4"}]},
"ietf-ipv6": {
"clients": [
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "1"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "2"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "3"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "4"}]}}}
"""
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_block = total_indices = 0
is_clear = is_changed = protocol = loop = 0
json_load = user_load = ""
ietfstring = "ietf-ipv4"
syslogaddress = syslogenable = syslogport = syslogsecure = None
syslogtransport = None
indices = []
addressarray = []
portarray = []
transportarray = []
securearray = []
for x in range(0, 5):
indices.insert(x, None)
addressarray.insert(x, None)
portarray.insert(x, None)
transportarray.insert(x, None)
securearray.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
# read in the list of syslog client addresses
total_block = 0
syslogaddress = cpmmodule.params['address']
if (syslogaddress is not None):
if isinstance(syslogaddress, list):
for x in syslogaddress:
addressarray[total_block] = to_native(x)
total_block += 1
# the number of idicies and addresses must match
if (total_indices > 0):
if (total_block != total_indices):
return is_changed, None
# read in the list of syslog client ports
total_block = 0
syslogport = cpmmodule.params['port']
if (syslogport is not None):
if isinstance(syslogport, list):
for x in syslogport:
portarray[total_block] = (int(to_native(x)))
total_block += 1
if (total_block > 0):
if (total_block != total_indices):
return is_changed, None
# read in the list of syslog client transport protocols
total_block = 0
syslogtransport = cpmmodule.params['transport']
if (syslogtransport is not None):
if isinstance(syslogtransport, list):
for x in syslogtransport:
transportarray[total_block] = (int(to_native(x)))
total_block += 1
if (total_block > 0):
if (total_block != total_indices):
return is_changed, None
# read in the list of syslog client secure enable
total_block = 0
syslogsecure = cpmmodule.params['secure']
if (syslogsecure is not None):
if isinstance(syslogsecure, list):
for x in syslogsecure:
securearray[total_block] = (int(to_native(x)))
total_block += 1
if (total_block > 0):
if (total_block != total_indices):
return is_changed, None
for x in range(0, total_indices):
if (addressarray[x] is not None):
if (loop > 0):
user_load = '%s,' % (user_load)
user_load = '%s{"index": "%d"' % (user_load, (indices[x] + 1))
if (addressarray[x] is not None):
if (existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["address"] != addressarray[x]):
is_changed = True
user_load = '%s,"address": "%s"' % (user_load, addressarray[x])
else:
user_load = '%s,"address": "%s"' % (user_load, existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["address"])
# see if the port number was changed
if (portarray[x] is not None):
if (int(existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["port"]) != portarray[x]):
is_changed = True
user_load = '%s,"port": "%s"' % (user_load, portarray[x])
else:
user_load = '%s,"port": "%s"' % (user_load, existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["port"])
# see if the transport type was changed
if (transportarray[x] is not None):
if (int(existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["transport"]) != transportarray[x]):
is_changed = True
user_load = '%s,"transport": "%s"' % (user_load, transportarray[x])
else:
user_load = '%s,"transport": "%s"' % (user_load, existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["transport"])
# see if the secure choice was changed
if (securearray[x] is not None):
if (int(existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["secure"]) != securearray[x]):
is_changed = True
user_load = '%s,"secure": "%s"' % (user_load, securearray[x])
else:
user_load = '%s,"secure": "%s"' % (user_load, existing_interface["syslogclient"][ietfstring]["clients"][(indices[x])]["secure"])
user_load = '%s}' % (user_load)
loop += 1
json_load = '{"syslogclient": [{ "%s": { "clear": %d, "change": %d' % (ietfstring, is_clear, is_changed)
if (len(user_load) > 0):
json_load = '%s, "clients": [ %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),
protocol=dict(type='int', required=False, default=0, choices=[0, 1]),
clear=dict(type='int', required=False, default=None, choices=[0, 1]),
index=dict(type='list', elements='raw', required=False, default=None),
address=dict(type='list', elements='raw', required=False),
port=dict(type='list', elements='raw', required=False),
transport=dict(type='list', elements='raw', required=False),
secure=dict(type='list', elements='raw', 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/syslogclient" % (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)
was_changed = False
result['data'] = json.loads(response.read())
was_changed, 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/syslogclient" % (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['data'] = response.read()
else:
result['data'] = json.loads('{"status": {"code": "-1", "text": "error with JSON and/or variables assembly"}}')
result['changed'] = was_changed
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,200 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2019 Red Hat Inc.
# Copyright (C) 2021 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 SYSLOG Client 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_syslog_client_info
version_added: "2.11.0"
author:
- "Western Telematic Inc. (@wtinetworkgear)"
short_description: Get network SYSLOG Client parameters from WTI OOB and PDU devices
description:
- "Get network SYSLOG Client 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", "qmimux0" ]
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 SYSLOG Client 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 SYSLOG Client 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:
syslogclient:
description: Current k/v pairs of SYSLOG Client info for the WTI device after module execution.
returned: always
type: dict
sample: {"syslogclient": {
"ietf-ipv4": {
"clients": [
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "1"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "2"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "3"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "4"}]},
"ietf-ipv6": {
"clients": [
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "1"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "2"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "3"},
{"address": "", "port": "514", "transport": "0", "secure": "0", "index": "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),
interface=dict(type='str', default=None, choices=["eth0", "eth1", "ppp0", "qmimux0"]),
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/syslogclient" % (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()

View File

@@ -0,0 +1,410 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (C) 2019 Red Hat Inc.
# Copyright (C) 2021 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 SYSLOG Server 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_syslog_server_config
version_added: "2.11.0"
author:
- "Western Telematic Inc. (@wtinetworkgear)"
short_description: Set network SYSLOG Server parameters in WTI OOB and PDU devices
description:
- "Set network SYSLOG Server 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:
- The ethernet port for the SYSLOG we are defining.
choices:
- eth0
- eth1
- ppp0
- qmimux0
required: true
type: str
protocol:
description:
- The protocol that the SYSLOG entry should be applied. 0 = ipv4, 1 = ipv6.
type: int
required: false
choices: [ 0, 1 ]
enable:
description:
- Activates SYSLOG listening for the specified interface and protocol.
type: int
required: false
choices: [ 0, 1 ]
port:
description:
- Defines the port number used by the SYSLOG Server (1 - 65535).
type: int
required: false
transport:
description:
- Defines the transfer protocol type used by the SYSLOG Server. 0=UDP, 1=TCP;
type: int
required: false
choices: [ 0, 1 ]
secure:
description:
- Defines if a secure connection is used by the SYSLOG Server (TCP Transport required).
type: int
required: false
choices: [ 0, 1 ]
clear:
description:
- Removes all the IP block entries for the protocol being defined before setting the newly defined entries.
type: int
required: false
choices: [ 0, 1 ]
index:
description:
- Index of the IP block being modified.
type: list
elements: raw
required: false
address:
description:
- Sets the IP Address to block message logging.
type: list
elements: raw
required: false
notes:
- Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.
"""
EXAMPLES = """
# Sets the device SYSLOG Server Parameters
- name: Set the an SYSLOG Server 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
interface: "eth0"
protocol: 0
port: 514
transport: 0
secure: 0
clear: 1
# Sets the device SYSLOG Server Parameters
- name: Set the SYSLOG Server Parameters a WTI device
cpm_iptables_config:
cpm_url: "nonexist.wti.com"
cpm_username: "super"
cpm_password: "super"
use_https: true
validate_certs: false
interface: "eth0"
protocol: 0
port: 514
transport: 0
secure: 0
clear: 1
index:
- 1
- 2
block:
- "192.168.50.4"
- "72.76.4.56"
"""
RETURN = """
data:
description: The output JSON returned from the commands sent
returned: always
type: complex
contains:
syslogserver:
description: Current k/v pairs of interface info for the WTI device after module execution.
returned: always
type: dict
sample: {"syslogserver": { "eth0": [ {"ietf-ipv4": {
"block": [{"address": "", "index": "1"}, {"address": "", "index": "2"},
{"address": "", "index": "3"}, {"address": "", "index": "4"}],
"enable": 0, "port": "514", "secure": "0", "transport": "0"},
"ietf-ipv6": {
"block": [{"address": "", "index": "1"}, {"address": "", "index": "2"},
{"address": "", "index": "3"}, {"address": "", "index": "4"}],
"enable": 0, "port": "514", "secure": "0", "transport": "0"}}]}}
"""
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_block = total_indices = 0
is_clear = is_changed = protocol = loop = 0
json_load = ""
ietfstring = "ietf-ipv4"
syslogenable = syslogport = syslogsecure = None
syslogtransport = None
user_load = ""
indices = []
blockarray = []
for x in range(0, 48):
indices.insert(x, None)
blockarray.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):
syslogenable = int(cpmmodule.params['enable'])
if (cpmmodule.params['port'] is not None):
syslogport = int(cpmmodule.params['port'])
if (cpmmodule.params['transport'] is not None):
syslogtransport = int(cpmmodule.params['transport'])
if (cpmmodule.params['secure'] is not None):
syslogsecure = int(cpmmodule.params['secure'])
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
total_block = 0
blockarray = cpmmodule.params['address']
if (blockarray is not None):
if isinstance(blockarray, list):
for x in blockarray:
blockarray[total_block] = to_native(x)
total_block += 1
if (total_indices > 0):
if (total_block != total_indices):
return is_changed, None
for x in range(0, total_block):
if (blockarray[x] is not None):
if (loop > 0):
user_load = '%s,' % (user_load)
user_load = '%s{"index": "%d"' % (user_load, (indices[x] + 1))
if (blockarray[x] is not None):
if (existing_interface["syslogserver"][ports][0][ietfstring]["block"][(indices[x])]["address"] != blockarray[x]):
is_changed = True
user_load = '%s,"address": "%s"' % (user_load, blockarray[x])
else:
user_load = '%s,"address": "%s"' % (user_load, existing_interface["syslogserver"][ports][0][ietfstring]["block"][(indices[x])]["address"])
user_load = '%s}' % (user_load)
loop += 1
json_load = '{"syslogserver": [{"%s": { "%s": { "clear": %d, "change": %d' % (ports, ietfstring, is_clear, is_changed)
if (syslogenable is not None):
if (int(existing_interface["syslogserver"][ports][0][ietfstring]["enable"]) != syslogenable):
is_changed = True
json_load = '%s, "enable": %d' % (json_load, syslogenable)
else:
json_load = '%s,"enable": "%s"' % (json_load, existing_interface["syslogserver"][ports][0][ietfstring]["enable"])
if (syslogport is not None):
if (int(existing_interface["syslogserver"][ports][0][ietfstring]["port"]) != syslogport):
is_changed = True
json_load = '%s, "port": %d' % (json_load, syslogport)
else:
json_load = '%s,"port": "%s"' % (json_load, existing_interface["syslogserver"][ports][0][ietfstring]["port"])
if (syslogtransport is not None):
if (int(existing_interface["syslogserver"][ports][0][ietfstring]["transport"]) != syslogtransport):
is_changed = True
json_load = '%s, "transport": %d' % (json_load, syslogtransport)
else:
json_load = '%s,"transport": "%s"' % (json_load, existing_interface["syslogserver"][ports][0][ietfstring]["transport"])
if (syslogsecure is not None):
if (int(existing_interface["syslogserver"][ports][0][ietfstring]["secure"]) != syslogsecure):
is_changed = True
json_load = '%s, "secure": %d' % (json_load, syslogsecure)
else:
json_load = '%s,"secure": "%s"' % (json_load, existing_interface["syslogserver"][ports][0][ietfstring]["secure"])
if (len(user_load) > 0):
json_load = '%s, "block": [ %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", "qmimux0"]),
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]),
port=dict(type='int', required=False, default=None),
transport=dict(type='int', required=False, default=None, choices=[0, 1]),
secure=dict(type='int', required=False, choices=[0, 1]),
index=dict(type='list', elements='raw', required=False, default=None),
address=dict(type='list', elements='raw', 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/syslogserver?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/syslogserver" % (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()

Some files were not shown because too many files have changed in this diff Show More