diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 16:03:42 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 16:03:42 +0000 |
commit | 66cec45960ce1d9c794e9399de15c138acb18aed (patch) | |
tree | 59cd19d69e9d56b7989b080da7c20ef1a3fe2a5a /ansible_collections/wti | |
parent | Initial commit. (diff) | |
download | ansible-66cec45960ce1d9c794e9399de15c138acb18aed.tar.xz ansible-66cec45960ce1d9c794e9399de15c138acb18aed.zip |
Adding upstream version 7.3.0+dfsg.upstream/7.3.0+dfsgupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
134 files changed, 23928 insertions, 0 deletions
diff --git a/ansible_collections/wti/remote/CHANGELOG.rst b/ansible_collections/wti/remote/CHANGELOG.rst new file mode 100644 index 00000000..993abea5 --- /dev/null +++ b/ansible_collections/wti/remote/CHANGELOG.rst @@ -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 +----------- + diff --git a/ansible_collections/wti/remote/FILES.json b/ansible_collections/wti/remote/FILES.json new file mode 100644 index 00000000..d80f21df --- /dev/null +++ b/ansible_collections/wti/remote/FILES.json @@ -0,0 +1,1076 @@ +{ + "files": [ + { + "name": ".", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "README.md", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "cc86b23fd8e6bc35895de4e8f18d7b3061501044501d93d0399171faafd535b3", + "format": 1 + }, + { + "name": "playbooks", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_plugcontrol", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_plugcontrol/plug_control.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3bb7a2d284ca0139d23376fd627bc5ceb0b9ea276ab7cf9697a666dffd90b287", + "format": 1 + }, + { + "name": "playbooks/cpm_plugcontrol/plug_control_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0260fa35fa36b7291d16dfa011784dda9656a4789a154531e205ec303e91e709", + "format": 1 + }, + { + "name": "playbooks/cpm_config", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_config/cpm_config_restore.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "dbe239f7c111ca703a49427172570006f7402d2c32344b66d1dc9a4b9d22228a", + "format": 1 + }, + { + "name": "playbooks/cpm_config/cpm_config_backup.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "eb8a081ede1ffa31a913b4e26a0f2d0a4ee333f99ddd8097e946c4a3a08a0553", + "format": 1 + }, + { + "name": "playbooks/cpm_time_date", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_time_date/time_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "916778518146bc6c6c9186da9ecf8fbe609e3cb19d0b9648e9078c9246e304f3", + "format": 1 + }, + { + "name": "playbooks/cpm_time_date/time_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "9e2db79afc89be1c9f2024f109971997b19c7db23b18b3001e1499ed471ed260", + "format": 1 + }, + { + "name": "playbooks/cpm_serial_ports", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_serial_ports/serial_ports_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "809180beb82d8a57d61b7b5f9187f815b53f8dfdd2181bfed167b92a5dc33318", + "format": 1 + }, + { + "name": "playbooks/cpm_serial_ports/serial_ports_action_set.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "027264d894a3bd33e9937cb2c39e0bb4ff59cd7b1156d416e66b8712c9177dab", + "format": 1 + }, + { + "name": "playbooks/cpm_serial_ports/serial_ports_action_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "da692a476a68e1e149f6bd2e81e921c684672b218ff778cdbc8a0529e4ee337a", + "format": 1 + }, + { + "name": "playbooks/cpm_serial_ports/serial_ports_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "da71edb810a3979b4c6f36e7b699f91df85c4686efc98d18199dce3cc2ae6d84", + "format": 1 + }, + { + "name": "playbooks/cpm_plugconfig", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_plugconfig/plug_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "aa407e11ef8b0de377d2d84f8bf26972101defd8f4b5380f6d58ca8b437f4ee4", + "format": 1 + }, + { + "name": "playbooks/cpm_plugconfig/plug_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8d5fd4f3ba38d7930a0c7b01858eef73c86d8ade20b14043a8d1bde5c23511b6", + "format": 1 + }, + { + "name": "playbooks/cpm_snmp", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_snmp/snmp_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a53441daa135f40ef99f5e1f4d79272be9427c6a2ac41c36cb5aa262bd5b1ec4", + "format": 1 + }, + { + "name": "playbooks/cpm_snmp/snmp_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "15d3d0a3362aa2d135781b469f62fc5feb955dfec8f1b74f4afaba46aaa3f9fa", + "format": 1 + }, + { + "name": "playbooks/cpm_hostname", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_hostname/hostname_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a1e80e62e0869d5a75bd32dfa723047bb8f7b71e97d444a459f6db5d61b6624e", + "format": 1 + }, + { + "name": "playbooks/cpm_hostname/hostname_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "81ca235ef41b70c978f1bb2954d999a70ea7ed01678e0cb5582efa3b5910b4cd", + "format": 1 + }, + { + "name": "playbooks/cpm_interface", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_interface/interface_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5ba6d3dc633ad8583652eee1fe568e87eea9470c8ab644640ce7e2be9acb2ce2", + "format": 1 + }, + { + "name": "playbooks/cpm_interface/interface_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bf0e98113eeb6198786befc06ba58da3ef91b64b8bbed2d404b90b228b39e95c", + "format": 1 + }, + { + "name": "playbooks/cpm_iptables", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_iptables/iptables_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e6d3091a82fc4e0a907761b8623b2a5481249040e45d4adec2e5184dc0106f0e", + "format": 1 + }, + { + "name": "playbooks/cpm_iptables/iptables_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ecf4bcbfe7833fc7e7cf028b1782ade9729ee6a22ce903b658571b27abeb31d2", + "format": 1 + }, + { + "name": "playbooks/cpm_status", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_status/power_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "784e761c9f17b4d633e115f136df2da004e2123fce1d46a8578819cf240ba87c", + "format": 1 + }, + { + "name": "playbooks/cpm_status/status_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "d27146b1f8948c8329aff03b4a1165d62ee1625a9431efd117908d87662749e9", + "format": 1 + }, + { + "name": "playbooks/cpm_status/current_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "81250969b8389fcf7b5dfca43c784687048a0802a2bb2ada7db13eb9eaa4d814", + "format": 1 + }, + { + "name": "playbooks/cpm_status/alarm_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c7eaeab3f0e4683b27db4c758823dead0f308c6f7e0813162b9ab3ac1eb172e9", + "format": 1 + }, + { + "name": "playbooks/cpm_status/temp_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6b433ae836d3a1c671e5fbcad371b9b401cd84012ef66cb259777edad2f24751", + "format": 1 + }, + { + "name": "playbooks/cpm_status/firmware_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "774637beb1cead454af209d1f2ddc82e73ddaf3bfdd0cebb62d4aa9d663e3a1a", + "format": 1 + }, + { + "name": "playbooks/cpm_syslog_client", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_syslog_client/syslog_client_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "27a8312607be119f05b44885b29d171400285cf7cecce2fc7e0612eb292cffa5", + "format": 1 + }, + { + "name": "playbooks/cpm_syslog_client/syslog_client_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ac15a9c7034f7cccc9990e287a0d004c8983907138b07e8e37b6a6776eff89ca", + "format": 1 + }, + { + "name": "playbooks/cpm_firmwareupdate", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_firmwareupdate/firmware_upgrade.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "7086ddef397ef488bddbb6dfbeffc6a883de452bb9a8e7c32f6a006a0ff821a6", + "format": 1 + }, + { + "name": "playbooks/cpm_syslog_server", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_syslog_server/syslog_server_info.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ec5b35850ddd85492e3e4533e9d605a6ac37fa663a6a843f8d241c034c0709a9", + "format": 1 + }, + { + "name": "playbooks/cpm_syslog_server/syslog_server_config.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "92a6eaa37ff7abcf45f23fcf2a30b1ef1024b1a380bf7e2cb63495c4ba1a1f6a", + "format": 1 + }, + { + "name": "playbooks/cpm_user", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "playbooks/cpm_user/user_edit.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "83a15cc70c80a409a479fea9837c82fb990fe5840202e1c6e60227e56f3f7347", + "format": 1 + }, + { + "name": "playbooks/cpm_user/user_add.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "736f066e4b3ea6cfd114cb43325a36a3cbcdb0fd89dc94c7bf9b021b2e73805c", + "format": 1 + }, + { + "name": "playbooks/cpm_user/user_get.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1e2751e5dbb52433d99d86bed47a2ceb06b12aceffc897383e698d5f9afe3a66", + "format": 1 + }, + { + "name": "playbooks/cpm_user/user_delete.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5a5012adaf8996706bc4c81cad7f92e7861652cd8e44481be3c3b740523ce3d8", + "format": 1 + }, + { + "name": "docs", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "docs/cpm_interface_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "cceabb837bef5f57eecec3e384316583efeefaa327731779c49788130dfeae8d", + "format": 1 + }, + { + "name": "docs/cpm_interface_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "38b500204ccbb64b70c02e2afcf0d2ac3b815ea519fbd3d9cdc806cbaae905cd", + "format": 1 + }, + { + "name": "docs/cpm_syslog_client_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ed3f96615c61c442dbc1d9f179a369f12823e6fef7a37b521aa6913800b64251", + "format": 1 + }, + { + "name": "docs/cpm_status_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "42db48949f51b96953643a68e3f3d7daf3f99ff486b805d08714688c5dacd773", + "format": 1 + }, + { + "name": "docs/cpm_serial_port_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "37d7ee114ed383549f2deabeff5d94122799354bfacb2b5f09643cecb7cf4c0e", + "format": 1 + }, + { + "name": "docs/cpm_alarm_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "01806a6ae5dfb24d8b7a72d2502bc0309f2f49f41bf9fbebbb27a206351d49d7", + "format": 1 + }, + { + "name": "docs/cpm_config_backup.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "874cf960b8d436850bba01b28a1b9035c5e907ad4b36e085c870e749e9215ef6", + "format": 1 + }, + { + "name": "docs/cpm_syslog_client_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0844fb4a7f6e2339e7b7707f923adedd26d9f11a60fc8185761215a1b83bc4d5", + "format": 1 + }, + { + "name": "docs/cpm_serial_port_action_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "fd2c2a98857d8078a0bbbf5e573babaa910bb51f4e41c921667e0bd94a1cb5ba", + "format": 1 + }, + { + "name": "docs/cpm_firmware_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e9ab6351bfa46127e3164e3ca79d8153e67e9d3a000ed9a95b4d9a05d272bbeb", + "format": 1 + }, + { + "name": "docs/cpm_firmware_update.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e3cec22ee95a4b40af596cd18321d62810e0aa30b9082e4a1934e8a5c365471b", + "format": 1 + }, + { + "name": "docs/cpm_current_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b87f0f19c80d68ef902533f9b1042454906088984ca0f37ebe0a91f8283a860a", + "format": 1 + }, + { + "name": "docs/cpm_syslog_server_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ce6330975e434703b3729d4c2e9f046b3e748019491e83d3f38973af5a906f05", + "format": 1 + }, + { + "name": "docs/cpm_snmp_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e83508504250081849ed60b876d3718c17b173a19a4011d18147495d59e3b2a0", + "format": 1 + }, + { + "name": "docs/cpm_plugcontrol.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "697b8765d50998e9c00c661f48cf3589219a15eb04da11ee16485c989ebe3884", + "format": 1 + }, + { + "name": "docs/cpm_temp_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3c70d59492f406e0ca1574751bd88809527c15adf7f21206cb5718e37cbda3c5", + "format": 1 + }, + { + "name": "docs/cpm_serial_port_action_set.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b1f09693503eb37d0d17990acb9924f8b16fec9e84744de24b4e1e3a51b6dd84", + "format": 1 + }, + { + "name": "docs/cpm_user.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c19c4cc43677e6fc4145f3964cab609b4603964eece17b26c81f2c2c5219cb51", + "format": 1 + }, + { + "name": "docs/cpm_power_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "67716c9fef3f09a6695f31ec48b9d75bd824325b635e351bb7affeaf0bf357d8", + "format": 1 + }, + { + "name": "docs/cpm_config_restore.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b0b342e6535752d8f7283692c1aa11320ddce8dffe0c1b06db45970d832188f9", + "format": 1 + }, + { + "name": "docs/cpm_plugconfig.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c6a572c88d470656f1c4d031e02310dc5c89d9ad9a1a1fb9d8667c8c2e725208", + "format": 1 + }, + { + "name": "docs/cpm_iptables_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ef22dc1a68ac50a8fc094bdca0005028e4133ce46cba241c1c10cb707f02a168", + "format": 1 + }, + { + "name": "docs/cpm_serial_port_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bb49a874cfa85c0b615e0322beceef9338d16e37b488c4d9603062592becc208", + "format": 1 + }, + { + "name": "docs/cpm_time_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c7c1fd0df687824433562fab8716ce9227ce73f292d41411a342aaa908b1bd57", + "format": 1 + }, + { + "name": "docs/cpm_iptables_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "43321c21a69a492bfb589d8c84ca5b1e1f828e6d31f602a44cdc99d72a49080a", + "format": 1 + }, + { + "name": "docs/cpm_snmp_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c2b85d7e98817b47d9f3ca882cb694cfe3e57b910acf3e9e04547ae1366b9ccc", + "format": 1 + }, + { + "name": "docs/cpm_hostname_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ec2d980eab128b2a4a2e9f97d781b1733168c782b14659130def6c4babf8dc72", + "format": 1 + }, + { + "name": "docs/cpm_time_info.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "eec02e5f84385423c9f0d585233be386a1c77ac87edfa812210a883de58700b7", + "format": 1 + }, + { + "name": "docs/cpm_hostname_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "d6df1366d4e2c785ebcbc14ac043a742fcfb0e1e15ef5d8fb409bd86fe94443e", + "format": 1 + }, + { + "name": "docs/cpm_syslog_server_config.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bf49689cd2e6bb74bcaf14cc8c2f50d1dc105887569a365eeb3a0b76ddcdd75f", + "format": 1 + }, + { + "name": "plugins", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/lookup", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/lookup/cpm_syslog_server_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "821e604059074e057eae002a181e20c90a8eb59eca262019fe76a059124a37bb", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_user.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1c1b08530d4755f2460d6447fd75760f3c141f659084f53d42dd149b4c7d7c1b", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_serial_port_action_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bc58eaa54a5ea0b06fc7a547d3ee9b34b5b0ba0108b127d9a12f72abe279449a", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_temp_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8c74bde6368fa1f22e4a3db33c6c59599d89818cace3905c13a4a990f62b1cde", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_status_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "54ca431466288106e2221a815c85d450e0d04ae3ef64adef4ec45035db41f9d8", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_syslog_server_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f9c15b936edc1e1ccacf8a9e6020976ceaa1d77b08ca96200dac503a5a20b7e2", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_interface_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "78b8a44d29c5488a067db746282dd113ffc177157e339b3f67d3842ccd5fdeaf", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_config_restore.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e7b927e3ebceef83778a30f97f94bffa4c40ac4041401a37761531959c720a0c", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_power_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "81ff6cab56343c0ab161960544ad1de2a1def773a2579aef3e8763ef99554a86", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_plugconfig.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3a9a218f323899cabe2dcf2650df8120895e77eca5512a3d97fe2b4e8b2de901", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_iptables_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "35bea84289a4ff6cfa57184b7b0ed774e427f93ca98cca6a69f5f35cd2275b37", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_snmp_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "efdd915a031f458643a7d483915275bc0c8c6360c03b8db7918c72ca359f27e5", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_firmware_update.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "df4935b03cd9d2544cda3d7ae35c8a9389558c605b0fcd8d0b8d1d6420cf3b6b", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_metering.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0a0283ef48e8b15a9c727e2e2def8016836ec0fbd60d9bd7c6368bdddd9a5aef", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_iptables_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e915743bf955a02467c1c75d66849064a70fae6400a59ec25123f62958a32657", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_firmware_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c696640c6ef51d232ccfbd567526ae16a24e267e129f67dc9de236c9cd628983", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_status.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4e6283c9157004b35dbf71792f64499571eb50b0f36e18e7520be6683285e647", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_serial_port_action_set.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6f1f7467f4fb2e72325ad5166e07bd878642469df73234c54207a57144107939", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_hostname_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "fe7d1ddfab3e8045c1b6760456d339480ae674b03c0558e541755370d825cf92", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_interface_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c64869afa0bebee9535c6d193425de5dfddfc40ef94f45da6f8b6ac7b73c5160", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_snmp_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8c03196b37e3053ee452b0d4cff3ee9e23821ce8c5a5ef431c7a2b745ac08351", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_alarm_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bba40f83e4e74c60bf843aa89e9abe69c84a046be6f86459db1be8c90803bc5c", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_hostname_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "12f63b470829c6800de6a6246f258633748509c3650d67fd2d0a555e50c7acb2", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_time_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3d57a01bbcb00cc28c16aebd87d8c520c1a7e764e4b80a8ffff9a549becd83d9", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_current_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1afe0276e62c2c786547376e8c026664166f64d9fdc4a996abaa0d12885d7def", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_config_backup.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e96543da3d052045f5aa89b68140c14fc7880de6927a216da38749d145c9f081", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_serial_port_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "39a12b7302b15b465bb7bb20a3d316043bf2f59dfdb45e324630b2aa5937175a", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_time_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2fd4b00fac09af65ff30601af508b14e423da424f08706e91d532f622aa6a9ba", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_plugcontrol.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6c650c0e10975251b583ed49e2da95f261472014cf2c73b02329c31b8c28273f", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_syslog_client_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a791df20e6e4f850285db4023d302ed8efa42df6ae7356e8b1ed649a56b92851", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_serial_port_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "241be234163dc68e6a4921dcae9ef8db41c31cb542bb36642a0557a34bd8f266", + "format": 1 + }, + { + "name": "plugins/lookup/cpm_syslog_client_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e6b99f8766dc44ddf7eaeba8b536b5a74ecd82cbef4efe4d5061858cc238d14a", + "format": 1 + }, + { + "name": "plugins/modules", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "plugins/modules/cpm_syslog_server_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "f5f4f26631c5e35923468b57f2003143558e609790e4369060b4fd47affece01", + "format": 1 + }, + { + "name": "plugins/modules/cpm_user.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1c1b08530d4755f2460d6447fd75760f3c141f659084f53d42dd149b4c7d7c1b", + "format": 1 + }, + { + "name": "plugins/modules/cpm_serial_port_action_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "481546812a6712090c36ed85f156f465a93e2ece564da8ec570cc87307f51960", + "format": 1 + }, + { + "name": "plugins/modules/cpm_temp_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "8c74bde6368fa1f22e4a3db33c6c59599d89818cace3905c13a4a990f62b1cde", + "format": 1 + }, + { + "name": "plugins/modules/cpm_status_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "54ca431466288106e2221a815c85d450e0d04ae3ef64adef4ec45035db41f9d8", + "format": 1 + }, + { + "name": "plugins/modules/cpm_syslog_server_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5b6698fa7acb3c9e859567ae0e0e4a2cc1a85e4085032d01ace435432bcf8489", + "format": 1 + }, + { + "name": "plugins/modules/cpm_interface_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "0e5d975a7b2359d52be396b8f9200363f590296bbd9c3e8f224499251f2009c8", + "format": 1 + }, + { + "name": "plugins/modules/cpm_config_restore.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e7b927e3ebceef83778a30f97f94bffa4c40ac4041401a37761531959c720a0c", + "format": 1 + }, + { + "name": "plugins/modules/cpm_power_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "81ff6cab56343c0ab161960544ad1de2a1def773a2579aef3e8763ef99554a86", + "format": 1 + }, + { + "name": "plugins/modules/cpm_plugconfig.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3a9a218f323899cabe2dcf2650df8120895e77eca5512a3d97fe2b4e8b2de901", + "format": 1 + }, + { + "name": "plugins/modules/cpm_iptables_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6a7ac4963800665e1ea73ad1bc5806e891e73bce8141eb3412063ddf7da4a351", + "format": 1 + }, + { + "name": "plugins/modules/cpm_snmp_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e4960bf82017f960516fef797f22aec9ddfc14285fb6b2247c06edc5a2023127", + "format": 1 + }, + { + "name": "plugins/modules/cpm_firmware_update.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "46e1992c0c95a5cb092be401ac7093c023c02c3f60afc0db3043a00df41096a8", + "format": 1 + }, + { + "name": "plugins/modules/cpm_iptables_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e915743bf955a02467c1c75d66849064a70fae6400a59ec25123f62958a32657", + "format": 1 + }, + { + "name": "plugins/modules/cpm_firmware_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "c696640c6ef51d232ccfbd567526ae16a24e267e129f67dc9de236c9cd628983", + "format": 1 + }, + { + "name": "plugins/modules/cpm_serial_port_action_set.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6f1f7467f4fb2e72325ad5166e07bd878642469df73234c54207a57144107939", + "format": 1 + }, + { + "name": "plugins/modules/cpm_hostname_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "fe7d1ddfab3e8045c1b6760456d339480ae674b03c0558e541755370d825cf92", + "format": 1 + }, + { + "name": "plugins/modules/cpm_interface_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "30ff72f27b0502e0291937407edb6ba6c9ca380dc24d650542dbc11c9967798f", + "format": 1 + }, + { + "name": "plugins/modules/cpm_snmp_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "5524a189928475e96e8cdf8c45925e0a4f7ad9dcc492afa36d50b92376eb7b84", + "format": 1 + }, + { + "name": "plugins/modules/cpm_alarm_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "bba40f83e4e74c60bf843aa89e9abe69c84a046be6f86459db1be8c90803bc5c", + "format": 1 + }, + { + "name": "plugins/modules/cpm_hostname_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "12f63b470829c6800de6a6246f258633748509c3650d67fd2d0a555e50c7acb2", + "format": 1 + }, + { + "name": "plugins/modules/cpm_time_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "3d57a01bbcb00cc28c16aebd87d8c520c1a7e764e4b80a8ffff9a549becd83d9", + "format": 1 + }, + { + "name": "plugins/modules/cpm_current_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "1afe0276e62c2c786547376e8c026664166f64d9fdc4a996abaa0d12885d7def", + "format": 1 + }, + { + "name": "plugins/modules/cpm_config_backup.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "e96543da3d052045f5aa89b68140c14fc7880de6927a216da38749d145c9f081", + "format": 1 + }, + { + "name": "plugins/modules/cpm_serial_port_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "39a12b7302b15b465bb7bb20a3d316043bf2f59dfdb45e324630b2aa5937175a", + "format": 1 + }, + { + "name": "plugins/modules/cpm_time_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "2fd4b00fac09af65ff30601af508b14e423da424f08706e91d532f622aa6a9ba", + "format": 1 + }, + { + "name": "plugins/modules/cpm_plugcontrol.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "6c650c0e10975251b583ed49e2da95f261472014cf2c73b02329c31b8c28273f", + "format": 1 + }, + { + "name": "plugins/modules/cpm_syslog_client_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4e2b423d20a9c4b3e7baeb631f41bd21a8de0e0712edce579039138ff3a41b38", + "format": 1 + }, + { + "name": "plugins/modules/cpm_serial_port_info.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "b61bf6ad74a9c116eb8eef487070255a81b11bab736e8faceef55cb505e67182", + "format": 1 + }, + { + "name": "plugins/modules/cpm_syslog_client_config.py", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "4256abd5789d75e4ad2e6ab27cbd606d5d1f6a03f22d60eaaa442d56559fc226", + "format": 1 + }, + { + "name": "requirements-wti.txt", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a88ffa5e594a4d9728e19ca3680bc163b3c6b96990da8caa2826ecb484c8376e", + "format": 1 + }, + { + "name": "meta", + "ftype": "dir", + "chksum_type": null, + "chksum_sha256": null, + "format": 1 + }, + { + "name": "meta/runtime.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "160bffa48efd4d1f846ecb7b5ab065ec919f165ad7840ab8db918519ca7c5c4d", + "format": 1 + }, + { + "name": "meta/execution-environment.yml", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "a98259cc52c11e7fbf90b4c659905c8fe395f821dec99a1a17a6fde984764f60", + "format": 1 + }, + { + "name": "CHANGELOG.rst", + "ftype": "file", + "chksum_type": "sha256", + "chksum_sha256": "ea537a47445538366f2e146177f33ae760c432f5177aa172327225a6858eb98c", + "format": 1 + } + ], + "format": 1 +}
\ No newline at end of file diff --git a/ansible_collections/wti/remote/MANIFEST.json b/ansible_collections/wti/remote/MANIFEST.json new file mode 100644 index 00000000..7f35a613 --- /dev/null +++ b/ansible_collections/wti/remote/MANIFEST.json @@ -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 +}
\ No newline at end of file diff --git a/ansible_collections/wti/remote/README.md b/ansible_collections/wti/remote/README.md new file mode 100644 index 00000000..7b7329c0 --- /dev/null +++ b/ansible_collections/wti/remote/README.md @@ -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) diff --git a/ansible_collections/wti/remote/docs/cpm_alarm_info.rst b/ansible_collections/wti/remote/docs/cpm_alarm_info.rst new file mode 100644 index 00000000..abed76b7 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_alarm_info.rst @@ -0,0 +1,123 @@ +.. _cpm_alarm_info_module: + + +cpm_alarm_info -- Get alarm information from WTI OOB and PDU devices +==================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get temperature alarm from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + alarms (success, dict, [{'name': 'OVER CURRENT (INITIAL)', 'status': '0'}, {'name': 'OVER CURRENT (CRITICAL)', 'status': '0'}, {'name': 'OVER TEMPERATURE (INITIAL)', 'status': '0'}]) + Current alarm status of the WTI device after module execution. + + + status (always, dict, {'code': '0', 'text': 'OK'}) + Return status after module completion + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_config_backup.rst b/ansible_collections/wti/remote/docs/cpm_config_backup.rst new file mode 100644 index 00000000..e8b87703 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_config_backup.rst @@ -0,0 +1,115 @@ +.. _cpm_config_backup_module: + + +cpm_config_backup -- Get parameters from WTI OOB and PDU devices +================================================================ + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to get the parameters from. + + + cpm_username (True, str, None) + This is the Username of the WTI device to get the parameters from. + + + cpm_password (True, str, None) + This is the Password of the WTI device to get the parameters from. + + + cpm_path (False, str, /tmp/) + This is the directory path to store the WTI device configuration file. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The XML configuration of the WTI device queried + + + status (success, list, [{'code': 0, 'savedfilename': '/tmp/wti-192-10-10-239-2020-02-13T16-05-57.xml', 'text': 'ok'}]) + List of status returns from backup operation + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_config_restore.rst b/ansible_collections/wti/remote/docs/cpm_config_restore.rst new file mode 100644 index 00000000..5ce45b46 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_config_restore.rst @@ -0,0 +1,125 @@ +.. _cpm_config_restore_module: + + +cpm_config_restore -- Send operational parameters to WTI OOB and PDU devices +============================================================================ + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Send operational parameters to WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to get the parameters from. + + + cpm_username (True, str, None) + This is the Username of the WTI device to get the parameters from. + + + cpm_password (True, str, None) + This is the Password of the WTI device to get the parameters from. + + + cpm_path (False, str, /tmp/) + This is the directory path to the existing the WTI device configuration file. + + + cpm_filename (True, str, None) + This is the filename of the existing WTI device configuration file. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output XML configuration of the WTI device queried + + + filelength (success, int, [{'filelength': 329439}]) + Length of the file uploaded in bytes + + + status (success, list, [{'code': 0, 'text': 'ok', 'unittimestamp': '2020-02-14T00:18:57+00:00'}]) + List of status returns from backup operation + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_current_info.rst b/ansible_collections/wti/remote/docs/cpm_current_info.rst new file mode 100644 index 00000000..a7b77977 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_current_info.rst @@ -0,0 +1,165 @@ +.. _cpm_current_info_module: + + +cpm_current_info -- Get the Current Information of a WTI device +=============================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get the Current Information of a WTI device + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + cpm_startdate (False, str, None) + Start date of the range to look for current data + + + cpm_enddate (False, str, None) + End date of the range to look for current data + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + timestamp (success, str, 2020-02-24T20:54:03+00:00) + Current timestamp of the WTI device after module execution. + + + powerunit (success, str, 1) + Identifies if the WTI device is a power type device. + + + outletmetering (success, str, 1) + Identifies if the WTI device has Poiwer Outlet metering. + + + ats (success, str, 1) + Identifies if the WTI device is an ATS type of power device. + + + plugcount (success, str, 8) + Current outlet plug count of the WTI device after module execution. + + + powerfactor (success, str, 100) + Power factor of the WTI device after module execution. + + + powereff (success, str, 100) + Power efficiency of the WTI device after module execution. + + + powerdatacount (success, str, 1) + Total powerdata samples returned after module execution. + + + powerdata (success, dict, [{'timestamp': '2020-02-24T23:29:31+00:00', 'temperature': '90', 'format': 'F', 'branch1': [{'voltage1': '118.00', 'current1': '0.00'}]}]) + Power data of the WTI device after module execution. + + + status (always, dict, {'code': '0', 'text': 'OK'}) + Return status after module completion + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_firmware_info.rst b/ansible_collections/wti/remote/docs/cpm_firmware_info.rst new file mode 100644 index 00000000..0ee38b33 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_firmware_info.rst @@ -0,0 +1,131 @@ +.. _cpm_firmware_info_module: + + +cpm_firmware_info -- Get firmware information from WTI OOB and PDU devices +========================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get firmware information from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + firmware (success, str, 6.60) + Current Firmware version of the WTI device. + + + family (success, str, 1) + Current family type (Console = 1 or Power = 0) of the WTI device. + + + fips (success, str, 2020-02-24T20:54:03+00:00) + If WTI device is a no FIPS only device. + + + status (always, dict, {'code': '0', 'text': 'OK'}) + Return status after module completion + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_firmware_update.rst b/ansible_collections/wti/remote/docs/cpm_firmware_update.rst new file mode 100644 index 00000000..37a25013 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_firmware_update.rst @@ -0,0 +1,145 @@ +.. _cpm_firmware_update_module: + + +cpm_firmware_update -- Set Serial port parameters in WTI OOB and PDU devices +============================================================================ + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set Serial port parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + cpm_path (False, str, /tmp/) + This is the directory path to store the WTI device configuration file. + + + cpm_file (False, str, None) + If a file is defined, this file will be used to update the WTI device. + + + use_force (False, bool, False) + If set to True, the upgrade will happen even if the device doesnt need it. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used - on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + family (False, int, 1) + Force the download to both either Console (1) or Power (0) + + + removefileonexit (False, int, 1) + After an upgrade, remove the upgrade OS image + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, complex, ) + The output XML configuration of the WTI device being updated + + + filelength (success, int, [{'filelength': 329439}]) + Length of the file uploaded in bytes + + + status (success, list, [{'code': 0}, {'text': 'ok'}, {'unittimestamp': '2020-02-14T00:18:57+00:00'}]) + List of status returns from backup operation + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_hostname_config.rst b/ansible_collections/wti/remote/docs/cpm_hostname_config.rst new file mode 100644 index 00000000..58cee626 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_hostname_config.rst @@ -0,0 +1,149 @@ +.. _cpm_hostname_config_module: + + +cpm_hostname_config -- Set Hostname (Site ID), Location, Asset Tag parameters in WTI OOB and PDU devices. +========================================================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set Hostname (Site ID), Location, Asset Tag parameters parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + hostname (False, str, None) + This is the Hostname (Site-ID) tag to be set for the WTI OOB and PDU device. + + + location (False, str, None) + This is the Location tag to be set for the WTI OOB and PDU device. + + + assettag (False, str, None) + This is the Asset Tag to be set for the WTI OOB and PDU device. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + timestamp (success, str, 2021-08-17T21:33:50+00:00) + Current timestamp of the WTI device after module execution. + + + hostname (success, str, myhostname) + Current Hostname (Site-ID) of the WTI device after module execution. + + + location (success, int, Irvine) + Current Location of the WTI device after module execution. + + + assettag (success, int, irvine92395) + Current Asset Tag of the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_hostname_info.rst b/ansible_collections/wti/remote/docs/cpm_hostname_info.rst new file mode 100644 index 00000000..15b5ff75 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_hostname_info.rst @@ -0,0 +1,131 @@ +.. _cpm_hostname_info_module: + + +cpm_hostname_info -- Get Hostname (Site ID), Location, Asset Tag parameters in WTI OOB and PDU devices +====================================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get Hostname (Site ID), Location, Asset Tag parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + timestamp (success, str, 2021-08-17T21:33:50+00:00) + Current timestamp of the WTI device after module execution. + + + hostname (success, str, myhostname) + Current Hostname (Site-ID) of the WTI device after module execution. + + + location (success, int, Irvine) + Current Location of the WTI device after module execution. + + + assettag (success, int, irvine92395) + Current Asset Tag of the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_interface_config.rst b/ansible_collections/wti/remote/docs/cpm_interface_config.rst new file mode 100644 index 00000000..68c211d8 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_interface_config.rst @@ -0,0 +1,196 @@ +.. _cpm_interface_config_module: + + +cpm_interface_config -- Set network interface parameters in WTI OOB and PDU devices +=================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set network interface parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + interface (False, str, None) + This is the ethernet port name that is getting configured. + + + negotiation (False, int, None) + 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 + + + ipv4address (False, str, None) + IPv4 format IP address for the defined interface Port. + + + ipv4netmask (False, str, None) + IPv4 format Netmask for the defined interface Port. + + + ipv4gateway (False, str, None) + IPv4 format Gateway address for the defined interface Port. + + + ipv4dhcpenable (False, int, None) + Enable IPv4 DHCP request call to obtain confufuration information. + + + ipv4dhcphostname (False, str, None) + Define IPv4 DHCP Hostname. + + + ipv4dhcplease (False, int, None) + IPv4 DHCP Lease Time. + + + ipv4dhcpobdns (False, int, None) + IPv6 DHCP Obtain DNS addresses auto. + + + ipv4dhcpupdns (False, int, None) + IPv4 DHCP DNS Server Update. + + + ipv4dhcpdefgateway (False, int, None) + Enable or Disable this ports configuration as the default IPv4 route for the device. + + + ipv6address (False, str, None) + IPv6 format IP address for the defined interface Port. + + + ipv6subnetprefix (False, str, None) + IPv6 format Subnet Prefix for the defined interface Port. + + + ipv6gateway (False, str, None) + IPv6 format Gateway address for the defined interface Port. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + totalports (success, int, 1) + Total interface ports requested of the WTI device. + + + interface (always, dict, {'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': ''}]}}) + Current k/v pairs of interface info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_interface_info.rst b/ansible_collections/wti/remote/docs/cpm_interface_info.rst new file mode 100644 index 00000000..89853ab5 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_interface_info.rst @@ -0,0 +1,136 @@ +.. _cpm_interface_info_module: + + +cpm_interface_info -- Get network interface parameters from WTI OOB and PDU devices +=================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get network interface parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + face (False, list, None) + 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. + + + interface (False, list, None) + 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. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + totalports (success, int, 1) + Total ethernet ports requested of the WTI device. + + + interface (always, dict, {'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': ''}]}}) + Current k/v pairs of interface info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_iptables_config.rst b/ansible_collections/wti/remote/docs/cpm_iptables_config.rst new file mode 100644 index 00000000..44cc50d4 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_iptables_config.rst @@ -0,0 +1,144 @@ +.. _cpm_iptables_config_module: + + +cpm_iptables_config -- Set network IPTables parameters in WTI OOB and PDU devices +================================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set network IPTables parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + protocol (False, int, None) + The protocol that the iptables entry should be applied. 0 = ipv4, 1 = ipv6. + + + index (False, list, None) + Index in which command should be inserted. If not defined entry will start at position one. + + + command (True, list, None) + Actual iptables command to send to the WTI device. + + + clear (False, int, None) + Removes all the iptables for the protocol being defined before setting the newly defined entry. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + iptables (always, dict, [{'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'}]}}}]) + Current k/v pairs of interface info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_iptables_info.rst b/ansible_collections/wti/remote/docs/cpm_iptables_info.rst new file mode 100644 index 00000000..0e930807 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_iptables_info.rst @@ -0,0 +1,119 @@ +.. _cpm_iptables_info_module: + + +cpm_iptables_info -- Get network IPTABLES parameters from WTI OOB and PDU devices +================================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get network IPTABLES parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + iptables (always, dict, {'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'}]}]}}]}) + Current k/v pairs of IPTABLES info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_plugconfig.rst b/ansible_collections/wti/remote/docs/cpm_plugconfig.rst new file mode 100644 index 00000000..09d1a497 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_plugconfig.rst @@ -0,0 +1,161 @@ +.. _cpm_plugconfig_module: + + +cpm_plugconfig -- Get and Set Plug Parameters on WTI OOB and PDU power devices +============================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get and Set Plug Parameters on WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_action (True, str, None) + This is the Action to send the module. + + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + plug_id (True, str, None) + 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. + + + plug_name (False, str, None) + The new name of the Plug. + + + plug_bootdelay (False, int, None) + 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'. + + + plug_default (False, int, None) + What the Plugs default state is when the device starts. 0 - Off, 1 - On. + + + plug_bootpriority (False, int, None) + 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. + + + + + + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, str, ) + The output JSON returned from the commands sent + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_plugcontrol.rst b/ansible_collections/wti/remote/docs/cpm_plugcontrol.rst new file mode 100644 index 00000000..76d9f59f --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_plugcontrol.rst @@ -0,0 +1,142 @@ +.. _cpm_plugcontrol_module: + + +cpm_plugcontrol -- Get and Set Plug actions on WTI OOB and PDU power devices +============================================================================ + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get and Set Plug actions on WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_action (True, str, None) + This is the Action to send the module. + + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + plug_id (True, str, None) + 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. + + + plug_state (False, str, None) + This is what action to take on the plug. + + + + + + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, str, ) + The output JSON returned from the commands sent + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_power_info.rst b/ansible_collections/wti/remote/docs/cpm_power_info.rst new file mode 100644 index 00000000..455546fa --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_power_info.rst @@ -0,0 +1,165 @@ +.. _cpm_power_info_module: + + +cpm_power_info -- Get the Power Information of a WTI device +=========================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get the Power Information of a WTI device + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + cpm_startdate (False, str, None) + Start date of the range to look for power data + + + cpm_enddate (False, str, None) + End date of the range to look for power data + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + timestamp (success, str, 2020-02-24T20:54:03+00:00) + Current timestamp of the WTI device after module execution. + + + powerunit (success, str, 1) + Identifies if the WTI device is a power type device. + + + outletmetering (success, str, 1) + Identifies if the WTI device has Poiwer Outlet metering. + + + ats (success, str, 1) + Identifies if the WTI device is an ATS type of power device. + + + plugcount (success, str, 8) + Current outlet plug count of the WTI device after module execution. + + + powerfactor (success, str, 100) + Power factor of the WTI device after module execution. + + + powereff (success, str, 100) + Power efficiency of the WTI device after module execution. + + + powerdatacount (success, str, 1) + Total powerdata samples returned after module execution. + + + powerdata (success, dict, [{'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'}]}]) + Power data of the WTI device after module execution. + + + status (always, dict, {'code': '0', 'text': 'OK'}) + Return status after module completion + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_serial_port_action_info.rst b/ansible_collections/wti/remote/docs/cpm_serial_port_action_info.rst new file mode 100644 index 00000000..98d31dd1 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_serial_port_action_info.rst @@ -0,0 +1,136 @@ +.. _cpm_serial_port_action_info_module: + + +cpm_serial_port_action_info -- Get Serial port connection status in WTI OOB and PDU devices +=========================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get Serial port connection status from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, False) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, False) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + port (optional, list, ['*']) + 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. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + ports (success, list, [{'port': 2, 'connstatus': 'Free'}, {'port': 4, 'connstatus': ' C-06'}]) + List of connection status for each serial port + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_serial_port_action_set.rst b/ansible_collections/wti/remote/docs/cpm_serial_port_action_set.rst new file mode 100644 index 00000000..892b2465 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_serial_port_action_set.rst @@ -0,0 +1,135 @@ +.. _cpm_serial_port_action_set_module: + + +cpm_serial_port_action_set -- Set Serial port connection/disconnection commands in WTI OOB and PDU devices +========================================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set Serial port connection/disconnection commands in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + port (True, int, None) + This is the port number that is getting the action performed on. + + + portremote (False, int, None) + This is the port number that is getting the action performed on. + + + action (False, int, None) + This is the baud rate to assign to the port. + + 1=Connect, 2=Disconnect + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, str, ) + The output JSON returned from the commands sent + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_serial_port_config.rst b/ansible_collections/wti/remote/docs/cpm_serial_port_config.rst new file mode 100644 index 00000000..2d3ef9fe --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_serial_port_config.rst @@ -0,0 +1,188 @@ +.. _cpm_serial_port_config_module: + + +cpm_serial_port_config -- Set Serial port parameters in WTI OOB and PDU devices +=============================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set Serial port parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + port (True, int, None) + This is the port number that is getting the action performed on. + + + portname (False, str, None) + This is the Name of the Port that is displayed. + + + baud (False, int, None) + 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 + + + handshake (False, int, None) + This is the handshake to assign to the port, 0=None, 1=XON/XOFF, 2=RTS/CTS, 3=Both. + + + stopbits (False, int, None) + This is the stop bits to assign to the port, 1=1 Stop Bit, 2=2 Stop Bit. + + + parity (False, int, None) + 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. + + + mode (False, int, None) + This is the port mode to assign to the port, 0=Any-to-Any. 1=Passive, 2=Buffer, 3=Modem, 4=ModemPPP. + + + cmd (False, int, None) + This is the Admin Mode to assign to the port, 0=Deny, 1=Permit. + + + seq (False, int, None) + This is the type of Sequence Disconnect to assign to the port, 1=Three Characters (before and after), 2=One Character Only, 3=Off + + + tout (False, int, None) + 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. + + + echo (False, bool, None) + -This is the command echo parameter to assign to the port, 0=Off, 1=On + + + break_allow (False, bool, None) + This is if the break character is allowed to be passed through the port, 0=Off, 1=On + + + logoff (False, str, None) + 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 + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, str, ) + The output JSON returned from the commands sent + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_serial_port_info.rst b/ansible_collections/wti/remote/docs/cpm_serial_port_info.rst new file mode 100644 index 00000000..d88fd390 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_serial_port_info.rst @@ -0,0 +1,136 @@ +.. _cpm_serial_port_info_module: + + +cpm_serial_port_info -- Get Serial port parameters in WTI OOB and PDU devices +============================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get Serial port parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, False) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, False) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + port (False, list, ['*']) + 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. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + serialports (success, list, [{'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}]) + List of data for each serial port + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_snmp_config.rst b/ansible_collections/wti/remote/docs/cpm_snmp_config.rst new file mode 100644 index 00000000..beb8c8f4 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_snmp_config.rst @@ -0,0 +1,223 @@ +.. _cpm_snmp_config_module: + + +cpm_snmp_config -- Set network IPTables parameters in WTI OOB and PDU devices +============================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set network IPTables parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + protocol (False, int, None) + The protocol that the SNMP entry should be applied. 0 = ipv4, 1 = ipv6. + + + enable (False, int, None) + The activates SNMP polling for the specified interface and protocol. + + + interface (True, str, None) + The ethernet port for the SNMP we are defining. + + + readonly (False, int, None) + Controls the ability to change configuration parameters with SNMP. + + + version (False, int, None) + Defined which version of SNMP the device will respond to 0 = V1/V2 Only, 1 = V3 Only, 2 = V1/V2/V3. + + + contact (False, str, None) + The name of the administrator responsible for SNMP issues. + + + location (False, str, None) + The location of the SNMP Server. + + + systemname (False, str, None) + The hostname of the WTI Device. + + + rocommunity (False, str, None) + Read Only Community Password, not used for SNMP V3. + + + rwcommunity (False, str, None) + Read/Write Community Password, not used for SNMP V3. + + + clear (False, int, None) + Removes all the users for the protocol being defined before setting the newly defined entries. + + + index (False, list, None) + Index of the user being modified (V3 only). + + + username (False, list, None) + Sets the User Name for SNMPv3 access (V3 only). + + + authpriv (False, list, None) + Configures the Authentication and Privacy features for SNMPv3 communication, 0 = Auth/NoPriv, 1 = Auth/Priv (V3 only). + + + authpass (False, list, None) + Sets the Authentication Password for SNMPv3 (V3 only). + + + authproto (False, list, None) + Which authentication protocol will be used, 0 = MD5, 1 = SHA1 (V3 only). + + + privpass (False, list, None) + Sets the Privacy Password for SNMPv3 (V3 only) (V3 only). + + + privproto (False, list, None) + Which privacy protocol will be used, 0 = DES, 1 = AES128 (V3 only). + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + snmpaccess (always, dict, [{'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'}]}}}]) + Current k/v pairs of interface info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_snmp_info.rst b/ansible_collections/wti/remote/docs/cpm_snmp_info.rst new file mode 100644 index 00000000..5ce92de3 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_snmp_info.rst @@ -0,0 +1,127 @@ +.. _cpm_snmp_info_module: + + +cpm_snmp_info -- Get network SNMP parameters from WTI OOB and PDU devices +========================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get network SNMP parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + interface (False, list, None) + 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. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + snmpaccess (always, dict, {'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'}]}]}}]}) + Current k/v pairs of SNMP info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_status_info.rst b/ansible_collections/wti/remote/docs/cpm_status_info.rst new file mode 100644 index 00000000..a65790d0 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_status_info.rst @@ -0,0 +1,227 @@ +.. _cpm_status_info_module: + + +cpm_status_info -- Get general status information from WTI OOB and PDU devices +============================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get temperature general status from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + vendor (success, str, wti) + Identifies WTI device as a WTI device. + + + product (success, str, CPM-800-1-CA) + Current Product Part Number of the WTI device. + + + totalports (success, str, 9) + Total serial ports of the WTI device. + + + totalplugs (success, str, 8) + Total Power Outlet plugs of the WTI device. + + + option1/2 (success, str, WPO-STRT-CPM8 / W4G-VZW-CPM8) + Various Identity options of the WTI. + + + softwareversion (success, str, 6.60 19 Feb 2020) + Expanded Firmware version of the WTI device. + + + serialnumber (success, str, 12345678901234) + Current Serial number of the WTI device. + + + assettag (success, str, ARTE121) + Current Asset Tag of the WTI device. + + + siteid (success, str, GENEVARACK) + Current Site-ID of the WTI device. + + + analogmodemphonenumber (success, str, 9495869959) + Current Analog Modem (if installed) Phone number of the WTI device. + + + modeminstalled (success, str, Yes, 4G/LTE) + Identifies if a modem is installed in the WTI device. + + + modemmodel (success, str, MTSMC-LVW2) + Identifies the modem model number (if installed) in the WTI device. + + + gig_dualphy (success, str, Yes, Yes) + Identifies dual ethernet port and gigabyte ethernet ports in the WTI device. + + + cpu_boardprogramdate (success, str, ARM, 4-30-2019) + Current Board and Program date of the WTI device. + + + ram_flash (success, str, 512 MB, 128 MB) + Total RAM and FLASH installed in the WTI device.. + + + lineinputcount_rating (success, str, 1 , 20 Amps) + Identifies total power inlets and their power rating. + + + currentmonitor (success, str, Yes) + Identifies if the unit has current monitoring capabilites. + + + keylength (success, str, 2048) + Current key length of the WTI device. + + + opensslversion (success, str, 1.1.1d 10 Sep 2019) + Current OpenSSL version running on the WTI device. + + + opensshversion (success, str, 8.2p1) + Current OpenSSH running on the WTI device. + + + apacheversion (success, str, 2.4.41) + Current Apache Web version running on the WTI device. + + + apirelease (success, str, March 2020) + Current Date of the API release of the WTI device. + + + uptime (success, str, 259308.26) + Current uptime of the WTI device. + + + energywise (success, str, 1.2.0) + Current Energywise version of the WTI device. + + + restful (success, str, v1.0, v2 (Mar20)) + Current RESTful version of the WTI device. + + + interface_list (success, str, eth0) + Current ethernet ports of the WTI device. + + + macaddresses (always, dict, {'mac': '00-09-9b-02-9a-26'}) + Current mac addresses of the WTI device. + + + status (always, dict, {'code': '0', 'text': 'OK'}) + Return status after module completion + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_syslog_client_config.rst b/ansible_collections/wti/remote/docs/cpm_syslog_client_config.rst new file mode 100644 index 00000000..791240cd --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_syslog_client_config.rst @@ -0,0 +1,176 @@ +.. _cpm_syslog_client_config_module: + + +cpm_syslog_client_config -- Set network SYSLOG Client parameters in WTI OOB and PDU devices +=========================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set network SYSLOG Client parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + protocol (False, int, None) + The protocol that the SYSLOG entry should be applied. 0 = ipv4, 1 = ipv6. + + + clear (False, int, None) + Removes all the IP block entries for the protocol being defined before setting the newly defined entries. + + + index (False, list, None) + Index of the IP block being modified. + + + address (False, list, None) + Sets the IP Address of the SYSLOG server to contact. + + + port (False, list, None) + Defines the port number used by the SYSLOG Client (1 - 65535). + + + transport (False, list, None) + Defines the transfer protocol type used by the SYSLOG Client. 0=UDP, 1=TCP; + + + secure (False, list, None) + Defines if a secure connection is used by the SYSLOG Client (TCP Transport required). + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + syslogclient (always, dict, {'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'}]}}}) + Current k/v pairs of interface info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_syslog_client_info.rst b/ansible_collections/wti/remote/docs/cpm_syslog_client_info.rst new file mode 100644 index 00000000..747d83c5 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_syslog_client_info.rst @@ -0,0 +1,127 @@ +.. _cpm_syslog_client_info_module: + + +cpm_syslog_client_info -- Get network SYSLOG Client parameters from WTI OOB and PDU devices +=========================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get network SYSLOG Client parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + interface (False, list, None) + 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. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + syslogclient (always, dict, {'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'}]}}}) + Current k/v pairs of SYSLOG Client info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_syslog_server_config.rst b/ansible_collections/wti/remote/docs/cpm_syslog_server_config.rst new file mode 100644 index 00000000..42732eba --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_syslog_server_config.rst @@ -0,0 +1,175 @@ +.. _cpm_syslog_server_config_module: + + +cpm_syslog_server_config -- Set network SYSLOG Server parameters in WTI OOB and PDU devices +=========================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set network SYSLOG Server parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + interface (True, list, None) + The ethernet port for the SYSLOG we are defining. + + + protocol (False, int, None) + The protocol that the SYSLOG entry should be applied. 0 = ipv4, 1 = ipv6. + + + enable (False, int, None) + Activates SYSLOG listening for the specified interface and protocol. + + + port (False, int, None) + Defines the port number used by the SYSLOG Server (1 - 65535). + + + transport (False, int, None) + Defines the transfer protocol type used by the SYSLOG Server. 0=UDP, 1=TCP; + + + secure (False, int, None) + Defines if a secure connection is used by the SYSLOG Server (TCP Transport required). + + + clear (False, int, None) + Removes all the IP block entries for the protocol being defined before setting the newly defined entries. + + + index (False, list, None) + Index of the IP block being modified. + + + address (False, list, None) + Sets the IP Address to block message logging. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + syslogserver (always, dict, {'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'}}]}}) + Current k/v pairs of interface info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_syslog_server_info.rst b/ansible_collections/wti/remote/docs/cpm_syslog_server_info.rst new file mode 100644 index 00000000..4a2a79c9 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_syslog_server_info.rst @@ -0,0 +1,127 @@ +.. _cpm_syslog_server_info_module: + + +cpm_syslog_server_info -- Get network SYSLOG Server parameters from WTI OOB and PDU devices +=========================================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get network SYSLOG Server parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + interface (False, list, None) + 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. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - name: Get the network SYSLOG Server 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 Server 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 Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + syslogserver (always, dict, {'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'}}]}}) + Current k/v pairs of SYSLOG Server info for the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_temp_info.rst b/ansible_collections/wti/remote/docs/cpm_temp_info.rst new file mode 100644 index 00000000..c249cb93 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_temp_info.rst @@ -0,0 +1,131 @@ +.. _cpm_temp_info_module: + + +cpm_temp_info -- Get temperature information from WTI OOB and PDU devices +========================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get temperature information from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + + - name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false + + + +Return Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + temperature (success, str, 76) + Current Temperature of the WTI device after module execution. + + + format (success, str, F) + Current Temperature format (Celsius or Fahrenheit) of the WTI device after module execution. + + + timestamp (success, str, 2020-02-24T20:54:03+00:00) + Current timestamp of the WTI device after module execution. + + + status (always, dict, {'code': '0', 'text': 'OK'}) + Return status after module completion + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_time_config.rst b/ansible_collections/wti/remote/docs/cpm_time_config.rst new file mode 100644 index 00000000..1194df07 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_time_config.rst @@ -0,0 +1,168 @@ +.. _cpm_time_config_module: + + +cpm_time_config -- Set Time/Date parameters in WTI OOB and PDU devices. +======================================================================= + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Set Time/Date and NTP parameters parameters in WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + date (False, str, None) + Static date in the format of two digit month, two digit day, four digit year separated by a slash symbol. + + + time (False, str, None) + Static time in the format of two digit hour, two digit minute, two digit second separated by a colon symbol. + + + timezone (False, int, None) + This is timezone that is assigned to the WTI device. + + + ntpenable (False, int, None) + This enables or disables the NTP client service. + + + ipv4address (False, str, None) + Comma separated string of up to two addresses for a primary and secondary IPv4 base NTP server. + + + ipv6address (False, str, None) + Comma separated string of up to two addresses for a primary and secondary IPv6 base NTP server. + + + timeout (False, int, None) + Set the network timeout in seconds of contacting the NTP servers, valid options can be from 1-60. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules. + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # Set a static time/date and timezone of a WTI device + - name: Set known fixed time/date of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + date: "12/12/2019" + time: "09:23:46" + timezone: 5 + + # Enable NTP and set primary and seconday servers of a WTI device + - name: Set NTP primary and seconday servers of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + timezone: 5 + ntpenable: 1 + ipv4address: "129.6.15.28.pool.ntp.org" + timeout: 15 + + + +Return Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + date (success, str, 11/14/2019) + Current Date of the WTI device after module execution. + + + time (success, str, 12:12:00) + Current Time of the WTI device after module execution. + + + timezone (success, int, 5) + Current Timezone of the WTI device after module execution. + + + ntp (always, dict, {'enable': '0', 'ietf-ipv4': {'address': [{'primary': '192.168.0.169', 'secondary': '12.34.56.78'}]}, 'ietf-ipv6': {'address': [{'primary': '', 'secondary': ''}]}, 'timeout': '4'}) + Current k/v pairs of ntp info of the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_time_info.rst b/ansible_collections/wti/remote/docs/cpm_time_info.rst new file mode 100644 index 00000000..c3603c5e --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_time_info.rst @@ -0,0 +1,131 @@ +.. _cpm_time_info_module: + + +cpm_time_info -- Get Time/Date parameters in WTI OOB and PDU devices +==================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get Time/Date and NTP parameters from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + + + +Notes +----- + +.. note:: + - Use ``groups/cpm`` in ``module_defaults`` to set common options used between CPM modules.) + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + - name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + + - name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false + + + +Return Values +------------- + +data (always, complex, ) + The output JSON returned from the commands sent + + + date (success, str, 11/14/2019) + Current Date of the WTI device after module execution. + + + time (success, str, 12:12:00) + Current Time of the WTI device after module execution. + + + timezone (success, int, 5) + Current Timezone of the WTI device after module execution. + + + ntp (always, dict, {'enable': '0', 'ietf-ipv4': {'address': [{'primary': '192.168.0.169', 'secondary': '12.34.56.78'}]}, 'ietf-ipv6': {'address': [{'primary': '', 'secondary': ''}]}, 'timeout': '4'}) + Current k/v pairs of ntp info of the WTI device after module execution. + + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/docs/cpm_user.rst b/ansible_collections/wti/remote/docs/cpm_user.rst new file mode 100644 index 00000000..8865f718 --- /dev/null +++ b/ansible_collections/wti/remote/docs/cpm_user.rst @@ -0,0 +1,221 @@ +.. _cpm_user_module: + + +cpm_user -- Get various status and parameters from WTI OOB and PDU devices +========================================================================== + +.. contents:: + :local: + :depth: 1 + + +Synopsis +-------- + +Get/Add/Edit Delete Users from WTI OOB and PDU devices + + + + + + +Parameters +---------- + + cpm_action (True, str, None) + This is the Action to send the module. + + + cpm_url (True, str, None) + This is the URL of the WTI device to send the module. + + + cpm_username (True, str, None) + This is the Basic Authentication Username of the WTI device to send the module. + + + cpm_password (True, str, None) + This is the Basic Authentication Password of the WTI device to send the module. + + + use_https (False, bool, True) + Designates to use an https connection or http connection. + + + validate_certs (False, bool, True) + If false, SSL certificates will not be validated. This should only be used + + on personally controlled sites using self-signed certificates. + + + use_proxy (False, bool, False) + Flag to control if the lookup will observe HTTP proxy environment variables when present. + + + user_name (True, str, None) + This is the User Name that needs to be create/modified/deleted + + + user_pass (False, str, None) + This is the User Password that needs to be create/modified/deleted + + If the user is being Created this parameter is required + + + user_accesslevel (False, int, None) + This is the access level that needs to be create/modified/deleted + + 0 View, 1 User, 2 SuperUser, 3 Administrator + + + user_accessssh (False, int, None) + If the user has access to the WTI device via SSH + + 0 No , 1 Yes + + + user_accessserial (False, int, None) + If the user has access to the WTI device via Serial ports + + 0 No , 1 Yes + + + user_accessweb (False, int, None) + If the user has access to the WTI device via Web + + 0 No , 1 Yes + + + user_accessapi (False, int, None) + If the user has access to the WTI device via RESTful APIs + + 0 No , 1 Yes + + + user_accessmonitor (False, int, None) + If the user has ability to monitor connection sessions + + 0 No , 1 Yes + + + user_accessoutbound (False, int, None) + If the user has ability to initiate Outbound connection + + 0 No , 1 Yes + + + user_portaccess (False, str, None) + If AccessLevel is lower than Administrator, which ports the user has access + + + user_plugaccess (False, str, None) + If AccessLevel is lower than Administrator, which plugs the user has access + + + user_groupaccess (False, str, None) + If AccessLevel is lower than Administrator, which Groups the user has access + + + user_callbackphone (False, str, None) + This is the Call Back phone number used for POTS modem connections + + + + + + + + + +Examples +-------- + +.. code-block:: yaml+jinja + + + # Get User Parameters + - name: Get the User Parameters for the given user of a WTI device + cpm_user: + cpm_action: "getuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" + + # Create User + - name: Create a User on a given WTI device + cpm_user: + cpm_action: "adduser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "complicatedpassword" + user_accesslevel: 2 + user_accessssh: 1 + user_accessserial: 1 + user_accessweb: 0 + user_accessapi: 1 + user_accessmonitor: 0 + user_accessoutbound: 0 + user_portaccess: "10011111" + user_plugaccess: "00000111" + user_groupaccess: "00000000" + + # Edit User + - name: Edit a User on a given WTI device + cpm_user: + cpm_action: "edituser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "newpasswordcomplicatedpassword" + + # Delete User + - name: Delete a User from a given WTI device + cpm_user: + cpm_action: "deleteuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" + + + +Return Values +------------- + +data (always, str, ) + The output JSON returned from the commands sent + + + + + +Status +------ + + + + +- This module is not guaranteed to have a backwards compatible interface. *[preview]* + + +- This module is maintained by community. + + + +Authors +~~~~~~~ + +- Western Telematic Inc. (@wtinetworkgear) + diff --git a/ansible_collections/wti/remote/meta/execution-environment.yml b/ansible_collections/wti/remote/meta/execution-environment.yml new file mode 100644 index 00000000..e947c060 --- /dev/null +++ b/ansible_collections/wti/remote/meta/execution-environment.yml @@ -0,0 +1,3 @@ +dependencies: + python: requirements-wti.txt +version: 1 diff --git a/ansible_collections/wti/remote/meta/runtime.yml b/ansible_collections/wti/remote/meta/runtime.yml new file mode 100644 index 00000000..6eeef346 --- /dev/null +++ b/ansible_collections/wti/remote/meta/runtime.yml @@ -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 + diff --git a/ansible_collections/wti/remote/playbooks/cpm_config/cpm_config_backup.yml b/ansible_collections/wti/remote/playbooks/cpm_config/cpm_config_backup.yml new file mode 100644 index 00000000..e7795ffb --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_config/cpm_config_backup.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_config/cpm_config_restore.yml b/ansible_collections/wti/remote/playbooks/cpm_config/cpm_config_restore.yml new file mode 100644 index 00000000..2a43e3db --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_config/cpm_config_restore.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_firmwareupdate/firmware_upgrade.yml b/ansible_collections/wti/remote/playbooks/cpm_firmwareupdate/firmware_upgrade.yml new file mode 100644 index 00000000..7fa155cd --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_firmwareupdate/firmware_upgrade.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_hostname/hostname_config.yml b/ansible_collections/wti/remote/playbooks/cpm_hostname/hostname_config.yml new file mode 100644 index 00000000..435d0f21 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_hostname/hostname_config.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_hostname/hostname_info.yml b/ansible_collections/wti/remote/playbooks/cpm_hostname/hostname_info.yml new file mode 100644 index 00000000..87822829 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_hostname/hostname_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_interface/interface_config.yml b/ansible_collections/wti/remote/playbooks/cpm_interface/interface_config.yml new file mode 100644 index 00000000..439b618a --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_interface/interface_config.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_interface/interface_info.yml b/ansible_collections/wti/remote/playbooks/cpm_interface/interface_info.yml new file mode 100644 index 00000000..9b967f47 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_interface/interface_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_iptables/iptables_config.yml b/ansible_collections/wti/remote/playbooks/cpm_iptables/iptables_config.yml new file mode 100644 index 00000000..6b80cf71 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_iptables/iptables_config.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_iptables/iptables_info.yml b/ansible_collections/wti/remote/playbooks/cpm_iptables/iptables_info.yml new file mode 100644 index 00000000..d0f9f87b --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_iptables/iptables_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_plugconfig/plug_config.yml b/ansible_collections/wti/remote/playbooks/cpm_plugconfig/plug_config.yml new file mode 100644 index 00000000..aa96a7e8 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_plugconfig/plug_config.yml @@ -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 }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_plugconfig/plug_info.yml b/ansible_collections/wti/remote/playbooks/cpm_plugconfig/plug_info.yml new file mode 100644 index 00000000..25bb39fe --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_plugconfig/plug_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_plugcontrol/plug_control.yml b/ansible_collections/wti/remote/playbooks/cpm_plugcontrol/plug_control.yml new file mode 100644 index 00000000..9a5b8306 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_plugcontrol/plug_control.yml @@ -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 }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_plugcontrol/plug_control_info.yml b/ansible_collections/wti/remote/playbooks/cpm_plugcontrol/plug_control_info.yml new file mode 100644 index 00000000..b5699be5 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_plugcontrol/plug_control_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_action_info.yml b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_action_info.yml new file mode 100644 index 00000000..ade866ef --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_action_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_action_set.yml b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_action_set.yml new file mode 100644 index 00000000..6794bc10 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_action_set.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_config.yml b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_config.yml new file mode 100644 index 00000000..fae8ff81 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_config.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_info.yml b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_info.yml new file mode 100644 index 00000000..4ac0d0dd --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_serial_ports/serial_ports_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_snmp/snmp_config.yml b/ansible_collections/wti/remote/playbooks/cpm_snmp/snmp_config.yml new file mode 100644 index 00000000..3eee8a22 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_snmp/snmp_config.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_snmp/snmp_info.yml b/ansible_collections/wti/remote/playbooks/cpm_snmp/snmp_info.yml new file mode 100644 index 00000000..357e8cf3 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_snmp/snmp_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_status/alarm_info.yml b/ansible_collections/wti/remote/playbooks/cpm_status/alarm_info.yml new file mode 100644 index 00000000..d132b9d9 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_status/alarm_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_status/current_info.yml b/ansible_collections/wti/remote/playbooks/cpm_status/current_info.yml new file mode 100644 index 00000000..356e5e9e --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_status/current_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_status/firmware_info.yml b/ansible_collections/wti/remote/playbooks/cpm_status/firmware_info.yml new file mode 100644 index 00000000..614347f6 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_status/firmware_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_status/power_info.yml b/ansible_collections/wti/remote/playbooks/cpm_status/power_info.yml new file mode 100644 index 00000000..da0ae80f --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_status/power_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_status/status_info.yml b/ansible_collections/wti/remote/playbooks/cpm_status/status_info.yml new file mode 100644 index 00000000..f34d963f --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_status/status_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_status/temp_info.yml b/ansible_collections/wti/remote/playbooks/cpm_status/temp_info.yml new file mode 100644 index 00000000..e8a8896a --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_status/temp_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_syslog_client/syslog_client_config.yml b/ansible_collections/wti/remote/playbooks/cpm_syslog_client/syslog_client_config.yml new file mode 100644 index 00000000..ed5ac92b --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_syslog_client/syslog_client_config.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_syslog_client/syslog_client_info.yml b/ansible_collections/wti/remote/playbooks/cpm_syslog_client/syslog_client_info.yml new file mode 100644 index 00000000..f51be682 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_syslog_client/syslog_client_info.yml @@ -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'] }}" + diff --git a/ansible_collections/wti/remote/playbooks/cpm_syslog_server/syslog_server_config.yml b/ansible_collections/wti/remote/playbooks/cpm_syslog_server/syslog_server_config.yml new file mode 100644 index 00000000..f9f149bb --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_syslog_server/syslog_server_config.yml @@ -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'] }}" + diff --git a/ansible_collections/wti/remote/playbooks/cpm_syslog_server/syslog_server_info.yml b/ansible_collections/wti/remote/playbooks/cpm_syslog_server/syslog_server_info.yml new file mode 100644 index 00000000..bd865e5a --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_syslog_server/syslog_server_info.yml @@ -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'] }}" + diff --git a/ansible_collections/wti/remote/playbooks/cpm_time_date/time_config.yml b/ansible_collections/wti/remote/playbooks/cpm_time_date/time_config.yml new file mode 100644 index 00000000..0580d081 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_time_date/time_config.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_time_date/time_info.yml b/ansible_collections/wti/remote/playbooks/cpm_time_date/time_info.yml new file mode 100644 index 00000000..e6dd887a --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_time_date/time_info.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_user/user_add.yml b/ansible_collections/wti/remote/playbooks/cpm_user/user_add.yml new file mode 100644 index 00000000..a15fe25d --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_user/user_add.yml @@ -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 }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_user/user_delete.yml b/ansible_collections/wti/remote/playbooks/cpm_user/user_delete.yml new file mode 100644 index 00000000..e6e45054 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_user/user_delete.yml @@ -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 }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_user/user_edit.yml b/ansible_collections/wti/remote/playbooks/cpm_user/user_edit.yml new file mode 100644 index 00000000..00dc46ba --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_user/user_edit.yml @@ -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'] }}" diff --git a/ansible_collections/wti/remote/playbooks/cpm_user/user_get.yml b/ansible_collections/wti/remote/playbooks/cpm_user/user_get.yml new file mode 100644 index 00000000..e782b4c2 --- /dev/null +++ b/ansible_collections/wti/remote/playbooks/cpm_user/user_get.yml @@ -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 }}" diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_alarm_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_alarm_info.py new file mode 100644 index 00000000..4adde44e --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_alarm_info.py @@ -0,0 +1,179 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI alarm information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_alarm_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_config_backup.py b/ansible_collections/wti/remote/plugins/lookup/cpm_config_backup.py new file mode 100644 index 00000000..d2a7f682 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_config_backup.py @@ -0,0 +1,204 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_config_backup +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_config_restore.py b/ansible_collections/wti/remote/plugins/lookup/cpm_config_restore.py new file mode 100644 index 00000000..eebe502e --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_config_restore.py @@ -0,0 +1,208 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_config_restore +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_current_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_current_info.py new file mode 100644 index 00000000..f2067cdc --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_current_info.py @@ -0,0 +1,241 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Current information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_current_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_firmware_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_firmware_info.py new file mode 100644 index 00000000..be724528 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_firmware_info.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI firmware information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_firmware_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_firmware_update.py b/ansible_collections/wti/remote/plugins/lookup/cpm_firmware_update.py new file mode 100644 index 00000000..fd69bacf --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_firmware_update.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_hostname_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_hostname_config.py new file mode 100644 index 00000000..6c19ca2b --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_hostname_config.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_hostname_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_hostname_info.py new file mode 100644 index 00000000..25e941d0 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_hostname_info.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_interface_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_interface_config.py new file mode 100644 index 00000000..afd495f9 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_interface_config.py @@ -0,0 +1,509 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to execute WTI network interface Parameters on WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_interface_config +version_added: "2.10.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_interface_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_interface_info.py new file mode 100644 index 00000000..952911c6 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_interface_info.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_iptables_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_iptables_config.py new file mode 100644 index 00000000..e3848921 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_iptables_config.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_iptables_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_iptables_info.py new file mode 100644 index 00000000..f90902ae --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_iptables_info.py @@ -0,0 +1,175 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Network IPTables Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_iptables_info +version_added: "2.10.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_metering.py b/ansible_collections/wti/remote/plugins/lookup/cpm_metering.py new file mode 100644 index 00000000..28aba7b5 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_metering.py @@ -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 diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_plugconfig.py b/ansible_collections/wti/remote/plugins/lookup/cpm_plugconfig.py new file mode 100644 index 00000000..27793eba --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_plugconfig.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_plugcontrol.py b/ansible_collections/wti/remote/plugins/lookup/cpm_plugcontrol.py new file mode 100644 index 00000000..b473b3ad --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_plugcontrol.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_power_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_power_info.py new file mode 100644 index 00000000..829617f9 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_power_info.py @@ -0,0 +1,242 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Power information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_power_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_action_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_action_info.py new file mode 100644 index 00000000..86799e39 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_action_info.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_action_set.py b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_action_set.py new file mode 100644 index 00000000..ab468fb5 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_action_set.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_config.py new file mode 100644 index 00000000..b6eb0f06 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_config.py @@ -0,0 +1,360 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to execute WTI Serial Port Parameters on WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_serial_port_config +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_info.py new file mode 100644 index 00000000..f112826c --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_serial_port_info.py @@ -0,0 +1,221 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Serial Port Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_serial_port_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_snmp_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_snmp_config.py new file mode 100644 index 00000000..4e4d4aab --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_snmp_config.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_snmp_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_snmp_info.py new file mode 100644 index 00000000..70ec37ea --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_snmp_info.py @@ -0,0 +1,193 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Network SNMP Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_snmp_info +version_added: "2.10.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_status.py b/ansible_collections/wti/remote/plugins/lookup/cpm_status.py new file mode 100644 index 00000000..f8cb326d --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_status.py @@ -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 diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_status_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_status_info.py new file mode 100644 index 00000000..a0e7b04e --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_status_info.py @@ -0,0 +1,307 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI general status information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_status_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_client_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_client_config.py new file mode 100644 index 00000000..0f8e24b4 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_client_config.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_client_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_client_info.py new file mode 100644 index 00000000..a1e3874c --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_client_info.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_server_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_server_config.py new file mode 100644 index 00000000..7f24990b --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_server_config.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_server_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_server_info.py new file mode 100644 index 00000000..87c804da --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_syslog_server_info.py @@ -0,0 +1,195 @@ +#!/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 Server 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_server_info +version_added: "2.11.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get network SYSLOG Server parameters from WTI OOB and PDU devices +description: + - "Get network SYSLOG Server 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 Server 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 Server 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: + syslogserver: + description: Current k/v pairs of SYSLOG Server 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"}}]}} +""" + +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/syslogserver" % (protocol, to_native(module.params['cpm_url']))) + ports = module.params['interface'] + + if (ports is not None): + if isinstance(ports, list): + ports = ','.join(to_native(x) for x in ports) + fullurl = ("%s?ports=%s" % (fullurl, ports)) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_temp_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_temp_info.py new file mode 100644 index 00000000..fcf913d9 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_temp_info.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI temperature information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_temp_info +version_added: "2.9.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get temperature information from WTI OOB and PDU devices +description: + - "Get temperature information from WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + type: bool + required: false + default: true + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: + - Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + temperature: + description: Current Temperature of the WTI device after module execution. + returned: success + type: str + sample: "76" + format: + description: Current Temperature format (Celsius or Fahrenheit) of the WTI device after module execution. + returned: success + type: str + sample: "F" + timestamp: + description: Current timestamp of the WTI device after module execution. + returned: success + type: str + sample: "2020-02-24T20:54:03+00:00" + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def run_module(): + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + fullurl = ("%s%s/api/v2/status/temperature" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_time_config.py b/ansible_collections/wti/remote/plugins/lookup/cpm_time_config.py new file mode 100644 index 00000000..1a003732 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_time_config.py @@ -0,0 +1,410 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to execute WTI time date Parameters on WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_time_config +version_added: "2.10.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Set Time/Date parameters in WTI OOB and PDU devices. +description: + - "Set Time/Date and NTP parameters parameters in WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + type: bool + required: false + default: true + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: + - Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false + date: + description: + - Static date in the format of two digit month, two digit day, four digit year separated by a slash symbol. + type: str + required: false + time: + description: + - Static time in the format of two digit hour, two digit minute, two digit second separated by a colon symbol. + type: str + required: false + timezone: + description: + - This is timezone that is assigned to the WTI device. + type: int + required: false + ntpenable: + description: + - This enables or disables the NTP client service. + type: int + required: false + choices: [ 0, 1 ] + ipv4address: + description: + - Comma separated string of up to two addresses for a primary and secondary IPv4 base NTP server. + type: str + required: false + ipv6address: + description: + - Comma separated string of up to two addresses for a primary and secondary IPv6 base NTP server. + type: str + required: false + timeout: + description: + - Set the network timeout in seconds of contacting the NTP servers, valid options can be from 1-60. + type: int + required: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Set a static time/date and timezone of a WTI device +- name: Set known fixed time/date of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + date: "12/12/2019" + time: "09:23:46" + timezone: 5 + +# Enable NTP and set primary and seconday servers of a WTI device +- name: Set NTP primary and seconday servers of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + timezone: 5 + ntpenable: 1 + ipv4address: "129.6.15.28.pool.ntp.org" + timeout: 15 +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + date: + description: Current Date of the WTI device after module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description: Current Time of the WTI device after module execution. + returned: success + type: str + sample: "12:12:00" + timezone: + description: Current Timezone of the WTI device after module execution. + returned: success + type: int + sample: 5 + ntp: + description: Current k/v pairs of ntp info of the WTI device after module execution. + returned: always + type: dict + sample: {"enable": "0", + "ietf-ipv4": {"address": [{"primary": "192.168.0.169","secondary": "12.34.56.78"}]}, + "ietf-ipv6": {"address": [{"primary": "","secondary": ""}]}, + "timeout": "4"} +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def assemble_json(cpmmodule, existing): + total_change = 0 + json_load = ietfstring = "" + + localdate = localtime = localtimezone = localenable = localtimeout = None + + localprimary = [] + localsecondary = [] + + for x in range(0, 2): + localprimary.insert(x, None) + localsecondary.insert(x, None) + + if cpmmodule.params["date"] is not None: + if (existing["date"] != to_native(cpmmodule.params["date"])): + total_change = (total_change | 1) + localdate = to_native(cpmmodule.params["date"]) + if cpmmodule.params["time"] is not None: + if (existing["time"] != to_native(cpmmodule.params["time"])): + total_change = (total_change | 2) + localtime = to_native(cpmmodule.params["time"]) + if cpmmodule.params["timezone"] is not None: + if (existing["timezone"] != to_native(cpmmodule.params["timezone"])): + total_change = (total_change | 4) + localtimezone = to_native(cpmmodule.params["timezone"]) + if cpmmodule.params["ntpenable"] is not None: + if (existing["ntp"]["enable"] != to_native(cpmmodule.params["ntpenable"])): + total_change = (total_change | 16) + localenable = to_native(cpmmodule.params["ntpenable"]) + if cpmmodule.params["ipv4address"] is not None: + loopcounter = 0 + portspassed = cpmmodule.params["ipv4address"].split(",") + for val in portspassed: + if (loopcounter == 0): + if (existing["ntp"]["ietf-ipv4"]["address"][0]["primary"] != to_native(val)): + total_change = (total_change | 32) + localprimary[0] = to_native(val) + loopcounter += 1 + else: + if (existing["ntp"]["ietf-ipv4"]["address"][0]["secondary"] != to_native(val)): + total_change = (total_change | 32) + localsecondary[0] = to_native(val) + loopcounter += 1 + if cpmmodule.params["ipv6address"] is not None: + loopcounter = 0 + portspassed = cpmmodule.params["ipv6address"].split(",") + for val in portspassed: + if (loopcounter == 0): + if (existing["ntp"]["ietf-ipv6"]["address"][0]["primary"] != to_native(val)): + total_change = (total_change | 64) + localprimary[1] = to_native(val) + loopcounter += 1 + else: + if (existing["ntp"]["ietf-ipv6"]["address"][0]["secondary"] != to_native(val)): + total_change = (total_change | 64) + localsecondary[1] = to_native(val) + loopcounter += 1 + if cpmmodule.params["timeout"] is not None: + if (existing["ntp"]["timeout"] != to_native(cpmmodule.params["timeout"])): + if ((int(to_native(cpmmodule.params["timeout"])) > 0) and (int(to_native(cpmmodule.params["timeout"])) <= 60)): + total_change = (total_change | 8) + localtimeout = to_native(cpmmodule.params["timeout"]) + + if (total_change > 0): + protocol = protocolchanged = 0 + ietfstring = "" + + if (localdate is not None): + ietfstring = '%s"date": "%s"' % (ietfstring, localdate) + + if (localtime is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"time": "%s"' % (ietfstring, localtime) + + if (localtimezone is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"timezone": "%s"' % (ietfstring, localtimezone) + + if ((localenable is not None) or (localtimeout is not None) or + (localprimary[0] is not None) or (localsecondary[0] is not None) or + (localprimary[1] is not None) or (localsecondary[1] is not None)): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "ntp": {' % (ietfstring) + + if (localenable is not None): + ietfstring = '%s"enable": "%s"' % (ietfstring, localenable) + + if (localtimeout is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"timeout": "%s"' % (ietfstring, localtimeout) + + if ((localprimary[0] is not None) or (localsecondary[0] is not None)): + if ((localenable is not None) or (localtimeout is not None)): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "ietf-ipv4": { "address": [{' % (ietfstring) + + if (localprimary[0] is not None): + ietfstring = '%s "primary": "%s"' % (ietfstring, localprimary[0]) + + if (localsecondary[0] is not None): + if (localprimary[0] is not None): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "secondary": "%s"' % (ietfstring, localsecondary[0]) + + # end ietf-ipv4 block + ietfstring = '%s }]}' % (ietfstring) + + if ((localprimary[1] is not None) or (localsecondary[1] is not None)): + if ((localprimary[0] is not None) or (localsecondary[0] is not None) or + (localenable is not None) or (localtimeout is not None)): + ietfstring = '%s,' % (ietfstring) + + ietfstring = '%s "ietf-ipv6": { "address": [{' % (ietfstring) + + if (localprimary[1] is not None): + ietfstring = '%s "primary": "%s"' % (ietfstring, localprimary[1]) + + if (localsecondary[1] is not None): + if (localprimary[1] is not None): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "secondary": "%s"' % (ietfstring, localsecondary[1]) + + # end ietf-ipv6 block + ietfstring = '%s }]}' % (ietfstring) + # end ntp block + ietfstring = '%s}' % (ietfstring) + + json_load = "{" + json_load = '%s%s' % (json_load, ietfstring) + json_load = '%s}' % (json_load) + else: + json_load = None + return json_load + + +def run_module(): + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + date=dict(type='str', required=False, default=None), + time=dict(type='str', required=False, default=None), + timezone=dict(type='int', required=False, default=None), + ntpenable=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4address=dict(type='str', required=False, default=None), + ipv6address=dict(type='str', required=False, default=None), + timeout=dict(type='int', required=False, default=None), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + fullurl = ("%s%s/api/v2/config/timedate" % (protocol, to_native(module.params['cpm_url']))) + method = 'GET' + try: + response = open_url(fullurl, data=None, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = response.read() + payload = assemble_json(module, json.loads(result['data'])) + + if module.check_mode: + if payload is not None: + result['changed'] = True + else: + if payload is not None: + fullurl = ("%s%s/api/v2/config/timedate" % (protocol, to_native(module.params['cpm_url']))) + method = 'POST' + + try: + response = open_url(fullurl, data=payload, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='POST: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='POST: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='POST: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='POST: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['changed'] = True + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_time_info.py b/ansible_collections/wti/remote/plugins/lookup/cpm_time_info.py new file mode 100644 index 00000000..8b8409dd --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_time_info.py @@ -0,0 +1,190 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI time date Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_time_info +version_added: "2.10.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get Time/Date parameters in WTI OOB and PDU devices +description: + - "Get Time/Date and NTP parameters from WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + type: bool + required: false + default: true + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: + - Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + date: + description: Current Date of the WTI device after module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description: Current Time of the WTI device after module execution. + returned: success + type: str + sample: "12:12:00" + timezone: + description: Current Timezone of the WTI device after module execution. + returned: success + type: int + sample: 5 + ntp: + description: Current k/v pairs of ntp info of the WTI device after module execution. + returned: always + type: dict + sample: {"enable": "0", + "ietf-ipv4": {"address": [{"primary": "192.168.0.169","secondary": "12.34.56.78"}]}, + "ietf-ipv6": {"address": [{"primary": "","secondary": ""}]}, + "timeout": "4"} +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def run_module(): + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + fullurl = ("%s%s/api/v2/config/timedate" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/lookup/cpm_user.py b/ansible_collections/wti/remote/plugins/lookup/cpm_user.py new file mode 100644 index 00000000..ffab07f1 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/lookup/cpm_user.py @@ -0,0 +1,355 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2018 Red Hat Inc. +# Copyright (C) 2018 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to execute CPM User Commands on WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_user +version_added: "2.7.0" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get various status and parameters from WTI OOB and PDU devices +description: + - "Get/Add/Edit Delete Users from WTI OOB and PDU devices" +options: + cpm_action: + description: + - This is the Action to send the module. + required: true + type: str + choices: [ "getuser", "adduser", "edituser", "deleteuser" ] + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Basic Authentication Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Basic Authentication Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + required: false + default: true + type: bool + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false + user_name: + description: + - This is the User Name that needs to be create/modified/deleted + type: str + required: true + user_pass: + description: + - This is the User Password that needs to be create/modified/deleted + - If the user is being Created this parameter is required + type: str + required: false + user_accesslevel: + description: + - This is the access level that needs to be create/modified/deleted + - 0 View, 1 User, 2 SuperUser, 3 Administrator + type: int + required: false + choices: [ 0, 1, 2, 3 ] + user_accessssh: + description: + - If the user has access to the WTI device via SSH + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessserial: + description: + - If the user has access to the WTI device via Serial ports + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessweb: + description: + - If the user has access to the WTI device via Web + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessapi: + description: + - If the user has access to the WTI device via RESTful APIs + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessmonitor: + description: + - If the user has ability to monitor connection sessions + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessoutbound: + description: + - If the user has ability to initiate Outbound connection + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_portaccess: + description: + - If AccessLevel is lower than Administrator, which ports the user has access + type: str + required: false + user_plugaccess: + description: + - If AccessLevel is lower than Administrator, which plugs the user has access + type: str + required: false + user_groupaccess: + description: + - If AccessLevel is lower than Administrator, which Groups the user has access + type: str + required: false + user_callbackphone: + description: + - This is the Call Back phone number used for POTS modem connections + type: str + required: false + """ + +EXAMPLES = """ +# Get User Parameters +- name: Get the User Parameters for the given user of a WTI device + cpm_user: + cpm_action: "getuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" + +# Create User +- name: Create a User on a given WTI device + cpm_user: + cpm_action: "adduser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "complicatedpassword" + user_accesslevel: 2 + user_accessssh: 1 + user_accessserial: 1 + user_accessweb: 0 + user_accessapi: 1 + user_accessmonitor: 0 + user_accessoutbound: 0 + user_portaccess: "10011111" + user_plugaccess: "00000111" + user_groupaccess: "00000000" + +# Edit User +- name: Edit a User on a given WTI device + cpm_user: + cpm_action: "edituser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "newpasswordcomplicatedpassword" + +# Delete User +- name: Delete a User from a given WTI device + cpm_user: + cpm_action: "deleteuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +import base64 + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def assemble_json(cpmmodule): + json_load = '{"users":{"username": "%s"' % to_native((cpmmodule.params["user_name"])) + + # for Adding there must be a password present + if cpmmodule.params["user_pass"] is not None and (len(cpmmodule.params["user_pass"]) > 0): + json_load = '%s,"newpasswd": "%s"' % (json_load, to_native(cpmmodule.params["user_pass"])) + if cpmmodule.params["user_accesslevel"] is not None: + json_load = '%s,"accesslevel": %s' % (json_load, to_native(cpmmodule.params["user_accesslevel"])) + if cpmmodule.params["user_portaccess"] is not None: + json_load = '%s,"portaccess": %s' % (json_load, to_native(cpmmodule.params["user_portaccess"])) + if cpmmodule.params["user_plugaccess"] is not None: + json_load = '%s,"plugaccess": %s' % (json_load, to_native(cpmmodule.params["user_plugaccess"])) + if cpmmodule.params["user_groupaccess"] is not None: + json_load = '%s,"groupaccess": %s' % (json_load, to_native(cpmmodule.params["user_groupaccess"])) + if cpmmodule.params["user_accessserial"] is not None: + json_load = '%s,"accessserial": %s' % (json_load, to_native(cpmmodule.params["user_accessserial"])) + if cpmmodule.params["user_accessssh"] is not None: + json_load = '%s,"accessssh": %s' % (json_load, to_native(cpmmodule.params["user_accessssh"])) + if cpmmodule.params["user_accessweb"] is not None: + json_load = '%s,"accessweb": %s' % (json_load, to_native(cpmmodule.params["user_accessweb"])) + if cpmmodule.params["user_accessoutbound"] is not None: + json_load = '%s,"accessoutbound": %s' % (json_load, to_native(cpmmodule.params["user_accessoutbound"])) + if cpmmodule.params["user_accessapi"] is not None: + json_load = '%s,"accessapi": %s' % (json_load, to_native(cpmmodule.params["user_accessapi"])) + if cpmmodule.params["user_accessmonitor"] is not None: + json_load = '%s,"accessmonitor": %s' % (json_load, to_native(cpmmodule.params["user_accessmonitor"])) + if cpmmodule.params["user_callbackphone"] is not None: + json_load = '%s,"callbackphone": "%s"' % (json_load, to_native(cpmmodule.params["user_callbackphone"])) + + json_load = '%s}}' % (json_load) + + return json_load + + +def run_module(): + + module_args = dict( + cpm_action=dict(choices=['getuser', 'adduser', 'edituser', 'deleteuser'], required=True), + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True, no_log=False), + cpm_password=dict(type='str', required=True, no_log=True), + user_name=dict(type='str', required=True), + user_pass=dict(type='str', required=False, default=None, no_log=True), + user_accesslevel=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3]), + user_accessssh=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessserial=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessweb=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessapi=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessmonitor=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessoutbound=dict(type='int', required=False, default=None, choices=[0, 1]), + user_portaccess=dict(type='str', required=False, default=None), + user_plugaccess=dict(type='str', required=False, default=None), + user_groupaccess=dict(type='str', required=False, default=None), + user_callbackphone=dict(type='str', required=False, default=None), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + if module.check_mode: + return result + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + payload = None + if (module.params['cpm_action'] == 'getuser'): + fullurl = ("%s%s/api/v2/config/users?username=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['user_name']))) + method = 'GET' + elif (module.params['cpm_action'] == 'adduser'): + if module.params["user_pass"] is None or (len(module.params["user_pass"]) == 0): + module.fail_json(msg='user_pass not defined.', **result) + + payload = assemble_json(module) + fullurl = ("%s%s/api/v2/config/users" % (protocol, to_native(module.params['cpm_url']))) + method = 'POST' + elif (module.params['cpm_action'] == 'edituser'): + payload = assemble_json(module) + fullurl = ("%s%s/api/v2/config/users" % (protocol, to_native(module.params['cpm_url']))) + method = 'PUT' + elif (module.params['cpm_action'] == 'deleteuser'): + fullurl = ("%s%s/api/v2/config/users?username=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['user_name']))) + method = 'DELETE' + + try: + response = open_url(fullurl, data=payload, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + if (method != 'GET'): + result['changed'] = True + + except HTTPError as e: + fail_json = dict(msg='Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='Error connecting to for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = to_text(response.read()) + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_alarm_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_alarm_info.py new file mode 100644 index 00000000..4adde44e --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_alarm_info.py @@ -0,0 +1,179 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI alarm information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_alarm_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_config_backup.py b/ansible_collections/wti/remote/plugins/modules/cpm_config_backup.py new file mode 100644 index 00000000..d2a7f682 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_config_backup.py @@ -0,0 +1,204 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_config_backup +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_config_restore.py b/ansible_collections/wti/remote/plugins/modules/cpm_config_restore.py new file mode 100644 index 00000000..eebe502e --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_config_restore.py @@ -0,0 +1,208 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2020 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_config_restore +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_current_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_current_info.py new file mode 100644 index 00000000..f2067cdc --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_current_info.py @@ -0,0 +1,241 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Current information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_current_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_firmware_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_firmware_info.py new file mode 100644 index 00000000..be724528 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_firmware_info.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI firmware information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_firmware_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_firmware_update.py b/ansible_collections/wti/remote/plugins/modules/cpm_firmware_update.py new file mode 100644 index 00000000..ca49fe27 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_firmware_update.py @@ -0,0 +1,374 @@ +#!/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 + +try: + import requests + HAS_REQUESTS_LIBRARY = True +except ImportError: + HAS_REQUESTS_LIBRARY = False + +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 HAS_REQUESTS_LIBRARY is False: + fail_json = dict(msg='IMPORT: requests import not installed', changed=False) + module.fail_json(**fail_json) + + 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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_hostname_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_hostname_config.py new file mode 100644 index 00000000..6c19ca2b --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_hostname_config.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_hostname_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_hostname_info.py new file mode 100644 index 00000000..25e941d0 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_hostname_info.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_interface_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_interface_config.py new file mode 100644 index 00000000..d71aae8f --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_interface_config.py @@ -0,0 +1,513 @@ +#!/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. + required: false + type: str + choices: + - eth0 + - eth1 + - ppp0 + - qmimux0 + 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", required=False, choices=["eth0", "eth1", "ppp0", "qmimux0"]), + negotiation=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3, 4, 5, 6]), + ipv4address=dict(type='str', required=False, default=None), + ipv4netmask=dict(type='str', required=False, default=None), + ipv4gateway=dict(type='str', required=False, default=None), + ipv4dhcpenable=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4dhcphostname=dict(type='str', required=False, default=None), + ipv4dhcplease=dict(type='int', required=False, default=None), + ipv4dhcpobdns=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4dhcpupdns=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4dhcpdefgateway=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv6address=dict(type='str', required=False, default=None), + ipv6subnetprefix=dict(type='str', required=False, default=None), + ipv6gateway=dict(type='str', required=False, default=None), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + fullurl = ("%s%s/api/v2/config/interface?ports=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['interface']))) + method = 'GET' + try: + response = open_url(fullurl, data=None, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + payload = assemble_json(module, result['data']) + + if module.check_mode: + if payload is not None: + result['changed'] = True + else: + if payload is not None: + fullurl = ("%s%s/api/v2/config/interface?ports=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['interface']))) + method = 'POST' + + try: + response = open_url(fullurl, data=payload, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='POST: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='POST: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='POST: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='POST: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['changed'] = True + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_interface_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_interface_info.py new file mode 100644 index 00000000..57ada488 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_interface_info.py @@ -0,0 +1,208 @@ +#!/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. + required: false + type: list + elements: str + choices: + - eth0 + - eth1 + - ppp0 + - qmimux0 +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="list", elements="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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_iptables_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_iptables_config.py new file mode 100644 index 00000000..42d68789 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_iptables_config.py @@ -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 + elements: int + required: false + command: + description: + - Actual iptables command to send to the WTI device. + type: list + elements: str + required: true + clear: + description: + - Removes all the iptables for the protocol being defined before setting the newly defined entry. + type: int + required: false + choices: [ 0, 1 ] +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Set Network IPTables Parameters +- name: Set the an IPTables Parameter for a WTI device + cpm_iptables_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + command: "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT" + +# Sets multiple Network IPTables Parameters +- name: Set the IPTables Parameters a WTI device + cpm_iptables_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + index: + - 1 + - 2 + command: + - "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT" + - "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + iptables: + description: Current k/v pairs of interface info for the WTI device after module execution. + returned: always + type: dict + sample: [{ "eth0": { "ietf-ipv4": { "clear": 1, "entries": [ + { "entry": "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT", "index": "1" }, + {"entry": "iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT", "index": "2" }]}}}] +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def assemble_json(cpmmodule, existing_interface): + total_change = total_commands = total_indices = 0 + is_clear = is_changed = protocol = 0 + negotiation = None + json_load = "" + ietfstring = "ietf-ipv4" + + indices = [] + commands = [] + + for x in range(0, 48): + indices.insert(x, None) + commands.insert(x, None) + + if (cpmmodule.params['clear'] is not None): + is_clear = int(cpmmodule.params['clear']) + + if (cpmmodule.params['protocol'] is not None): + protocol = int(cpmmodule.params['protocol']) + if (protocol == 1): + ietfstring = "ietf-ipv6" + + index = cpmmodule.params['index'] + if (index is not None): + if isinstance(index, list): + for x in index: + indices.insert(total_indices, (int(to_native(x))) - 1) + total_indices += 1 + + command = cpmmodule.params['command'] + if (command is not None): + if isinstance(command, list): + for x in command: + if (total_indices == 0): + commands.insert(total_commands, to_native(x)) + else: + commands.insert(indices[total_commands], to_native(x)) + total_commands += 1 + + if (total_indices > 0): + if (total_commands != total_indices): + return None + + for x in range(0, 48): + if (commands[x] is not None): + if ((existing_interface["iptables"][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": { "%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='int', required=False, default=None), + command=dict(type='list', elements='str', required=True), + clear=dict(type='int', required=False, default=None, choices=[0, 1]), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + transport = "https://" + else: + transport = "http://" + + fullurl = ("%s%s/api/v2/config/iptables" % (transport, to_native(module.params['cpm_url']))) + method = 'GET' + try: + response = open_url(fullurl, data=None, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + payload = assemble_json(module, result['data']) + + if module.check_mode: + if (payload is not None) and (len(payload) > 0): + result['changed'] = True + else: + if (payload is not None) and (len(payload) > 0): + fullurl = ("%s%s/api/v2/config/iptables" % (transport, to_native(module.params['cpm_url']))) + method = 'POST' + + try: + response = open_url(fullurl, data=payload, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='POST: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='POST: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='POST: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='POST: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['changed'] = True + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_iptables_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_iptables_info.py new file mode 100644 index 00000000..f90902ae --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_iptables_info.py @@ -0,0 +1,175 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Network IPTables Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_iptables_info +version_added: "2.10.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_plugconfig.py b/ansible_collections/wti/remote/plugins/modules/cpm_plugconfig.py new file mode 100644 index 00000000..27793eba --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_plugconfig.py @@ -0,0 +1,272 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2018 Red Hat Inc. +# Copyright (C) 2018 Western Telematic Inc. <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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_plugcontrol.py b/ansible_collections/wti/remote/plugins/modules/cpm_plugcontrol.py new file mode 100644 index 00000000..b473b3ad --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_plugcontrol.py @@ -0,0 +1,234 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2018 Red Hat Inc. +# Copyright (C) 2018 Western Telematic Inc. <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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_power_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_power_info.py new file mode 100644 index 00000000..829617f9 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_power_info.py @@ -0,0 +1,242 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI Power information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_power_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_action_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_action_info.py new file mode 100644 index 00000000..da3d2795 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_action_info.py @@ -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: str + 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='str', 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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_action_set.py b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_action_set.py new file mode 100644 index 00000000..ab468fb5 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_action_set.py @@ -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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_config.py new file mode 100644 index 00000000..b6eb0f06 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_config.py @@ -0,0 +1,360 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to execute WTI Serial Port Parameters on WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_serial_port_config +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_info.py new file mode 100644 index 00000000..09b036af --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_serial_port_info.py @@ -0,0 +1,222 @@ +#!/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: str + required: false + 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='str', default=['*']), + use_https=dict(type='bool', default=False), + validate_certs=dict(type='bool', default=False), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + ports = module.params['port'] + if isinstance(ports, list): + ports = ','.join(to_native(x) for x in ports) + fullurl = ("%s%s/api/v2/config/serialports?ports=%s" % (protocol, to_native(module.params['cpm_url']), ports)) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_snmp_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_snmp_config.py new file mode 100644 index 00000000..57ca9437 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_snmp_config.py @@ -0,0 +1,614 @@ +#!/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. + required: true + type: str + choices: + - eth0 + - eth1 + - ppp0 + - qmimux0 + 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: int + required: false + username: + description: + - Sets the User Name for SNMPv3 access (V3 only). + type: list + elements: str + required: false + authpriv: + description: + - Configures the Authentication and Privacy features for SNMPv3 communication, 0 = Auth/NoPriv, 1 = Auth/Priv (V3 only). + type: list + elements: int + required: false + authpass: + description: + - Sets the Authentication Password for SNMPv3 (V3 only). + type: list + elements: str + required: false + authproto: + description: + - Which authentication protocol will be used, 0 = MD5, 1 = SHA1 (V3 only). + type: list + elements: int + required: false + privpass: + description: + - Sets the Privacy Password for SNMPv3 (V3 only) (V3 only). + type: list + elements: str + required: false + privproto: + description: + - Which privacy protocol will be used, 0 = DES, 1 = AES128 (V3 only). + type: list + elements: int + 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"][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"][ports][0][ietfstring]["users"][(indices[x])]["username"]) + + if (authpassarray[x] is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["users"][(indices[x])]["authpass"]) + + if (privpassarray[x] is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["users"][(indices[x])]["privpass"]) + + if (authpriv[x] is not None): + if (int(existing_interface["snmpaccess"][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"][ports][0][ietfstring]["users"][(indices[x])]["authpriv"]) + + if (authproto[x] is not None): + if (int(existing_interface["snmpaccess"][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"][ports][0][ietfstring]["users"][(indices[x])]["authproto"]) + + if (privproto[x] is not None): + if (int(existing_interface["snmpaccess"][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"][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"][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"][ports][0][ietfstring]["enable"]) + + if (snmpversion is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["version"]) + + if (snmpreadonly is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["readonly"]) + + if (snmpsystemname is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["systemname"]) + + if (snmpcontact is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["contact"]) + + if (snmplocation is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["location"]) + + if (snmprocommunity is not None): + if (existing_interface["snmpaccess"][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"][ports][0][ietfstring]["rocommunity"]) + + if (snmprwcommunity is not None): + if (existing_interface["snmpaccess"][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"][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), + contact=dict(type='str', required=False), + location=dict(type='str', required=False), + rocommunity=dict(type='str', required=False), + rwcommunity=dict(type='str', required=False), + index=dict(type='list', elements='int', required=False, default=None), + username=dict(type='list', elements='str', required=False), + authpriv=dict(type='list', elements='int', required=False, default=None), + authproto=dict(type='list', elements='int', required=False, default=None), + privproto=dict(type='list', elements='int', required=False, default=None), + authpass=dict(type='list', elements='str', required=False, no_log=True), + privpass=dict(type='list', elements='str', 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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_snmp_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_snmp_info.py new file mode 100644 index 00000000..4bef5868 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_snmp_info.py @@ -0,0 +1,198 @@ +#!/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. + required: false + type: list + elements: str + 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 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="list", elements="str", required=False, 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/snmpaccess" % (protocol, to_native(module.params['cpm_url']))) + ports = module.params['interface'] + + if (ports is not None): + if isinstance(ports, list): + ports = ','.join(to_native(x) for x in ports) + fullurl = ("%s?ports=%s" % (fullurl, ports)) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_status_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_status_info.py new file mode 100644 index 00000000..a0e7b04e --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_status_info.py @@ -0,0 +1,307 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI general status information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_status_info +version_added: "2.9.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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_syslog_client_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_client_config.py new file mode 100644 index 00000000..d6f26835 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_client_config.py @@ -0,0 +1,441 @@ +#!/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: int + required: false + address: + description: + - Sets the IP Address of the SYSLOG server to contact. + type: list + elements: str + required: false + port: + description: + - Defines the port number used by the SYSLOG Client (1 - 65535). + type: list + elements: int + required: false + transport: + description: + - Defines the transfer protocol type used by the SYSLOG Client. 0=UDP, 1=TCP; + type: list + elements: int + required: false + secure: + description: + - Defines if a secure connection is used by the SYSLOG Client (TCP Transport required). + type: list + elements: int + 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='int', required=False, default=None), + address=dict(type='list', elements='str', required=False), + port=dict(type='list', elements='int', required=False), + transport=dict(type='list', elements='int', required=False), + secure=dict(type='list', elements='int', 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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_syslog_client_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_client_info.py new file mode 100644 index 00000000..0529a824 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_client_info.py @@ -0,0 +1,205 @@ +#!/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. + required: false + type: list + elements: str + 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="list", elements="str", required=False, 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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_syslog_server_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_server_config.py new file mode 100644 index 00000000..fe8c1a1f --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_server_config.py @@ -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. + type: str + choices: + - eth0 + - eth1 + - ppp0 + - qmimux0 + required: true + 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: int + required: false + address: + description: + - Sets the IP Address to block message logging. + type: list + elements: str + 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='int', required=False, default=None), + address=dict(type='list', elements='str', required=False), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + transport = "https://" + else: + transport = "http://" + + fullurl = ("%s%s/api/v2/config/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() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_syslog_server_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_server_info.py new file mode 100644 index 00000000..d78e33dd --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_syslog_server_info.py @@ -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 Server 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_server_info +version_added: "2.11.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get network SYSLOG Server parameters from WTI OOB and PDU devices +description: + - "Get network SYSLOG Server 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. + required: false + type: list + elements: str + 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 Server 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 Server 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: + syslogserver: + description: Current k/v pairs of SYSLOG Server 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"}}]}} +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def run_module(): + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + interface=dict(type="list", elements="str", required=False, 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/syslogserver" % (protocol, to_native(module.params['cpm_url']))) + ports = module.params['interface'] + + if (ports is not None): + if isinstance(ports, list): + ports = ','.join(to_native(x) for x in ports) + fullurl = ("%s?ports=%s" % (fullurl, ports)) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_temp_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_temp_info.py new file mode 100644 index 00000000..fcf913d9 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_temp_info.py @@ -0,0 +1,187 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI temperature information from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_temp_info +version_added: "2.9.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get temperature information from WTI OOB and PDU devices +description: + - "Get temperature information from WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + type: bool + required: false + default: true + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: + - Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Temperature Information of a WTI device + cpm_temp_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + temperature: + description: Current Temperature of the WTI device after module execution. + returned: success + type: str + sample: "76" + format: + description: Current Temperature format (Celsius or Fahrenheit) of the WTI device after module execution. + returned: success + type: str + sample: "F" + timestamp: + description: Current timestamp of the WTI device after module execution. + returned: success + type: str + sample: "2020-02-24T20:54:03+00:00" + status: + description: Return status after module completion + returned: always + type: dict + sample: { "code": "0", "text": "OK" } +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def run_module(): + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + fullurl = ("%s%s/api/v2/status/temperature" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_time_config.py b/ansible_collections/wti/remote/plugins/modules/cpm_time_config.py new file mode 100644 index 00000000..1a003732 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_time_config.py @@ -0,0 +1,410 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to execute WTI time date Parameters on WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_time_config +version_added: "2.10.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Set Time/Date parameters in WTI OOB and PDU devices. +description: + - "Set Time/Date and NTP parameters parameters in WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + type: bool + required: false + default: true + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: + - Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false + date: + description: + - Static date in the format of two digit month, two digit day, four digit year separated by a slash symbol. + type: str + required: false + time: + description: + - Static time in the format of two digit hour, two digit minute, two digit second separated by a colon symbol. + type: str + required: false + timezone: + description: + - This is timezone that is assigned to the WTI device. + type: int + required: false + ntpenable: + description: + - This enables or disables the NTP client service. + type: int + required: false + choices: [ 0, 1 ] + ipv4address: + description: + - Comma separated string of up to two addresses for a primary and secondary IPv4 base NTP server. + type: str + required: false + ipv6address: + description: + - Comma separated string of up to two addresses for a primary and secondary IPv6 base NTP server. + type: str + required: false + timeout: + description: + - Set the network timeout in seconds of contacting the NTP servers, valid options can be from 1-60. + type: int + required: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules. +""" + +EXAMPLES = """ +# Set a static time/date and timezone of a WTI device +- name: Set known fixed time/date of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + date: "12/12/2019" + time: "09:23:46" + timezone: 5 + +# Enable NTP and set primary and seconday servers of a WTI device +- name: Set NTP primary and seconday servers of a WTI device + cpm_time_config: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + timezone: 5 + ntpenable: 1 + ipv4address: "129.6.15.28.pool.ntp.org" + timeout: 15 +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + date: + description: Current Date of the WTI device after module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description: Current Time of the WTI device after module execution. + returned: success + type: str + sample: "12:12:00" + timezone: + description: Current Timezone of the WTI device after module execution. + returned: success + type: int + sample: 5 + ntp: + description: Current k/v pairs of ntp info of the WTI device after module execution. + returned: always + type: dict + sample: {"enable": "0", + "ietf-ipv4": {"address": [{"primary": "192.168.0.169","secondary": "12.34.56.78"}]}, + "ietf-ipv6": {"address": [{"primary": "","secondary": ""}]}, + "timeout": "4"} +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def assemble_json(cpmmodule, existing): + total_change = 0 + json_load = ietfstring = "" + + localdate = localtime = localtimezone = localenable = localtimeout = None + + localprimary = [] + localsecondary = [] + + for x in range(0, 2): + localprimary.insert(x, None) + localsecondary.insert(x, None) + + if cpmmodule.params["date"] is not None: + if (existing["date"] != to_native(cpmmodule.params["date"])): + total_change = (total_change | 1) + localdate = to_native(cpmmodule.params["date"]) + if cpmmodule.params["time"] is not None: + if (existing["time"] != to_native(cpmmodule.params["time"])): + total_change = (total_change | 2) + localtime = to_native(cpmmodule.params["time"]) + if cpmmodule.params["timezone"] is not None: + if (existing["timezone"] != to_native(cpmmodule.params["timezone"])): + total_change = (total_change | 4) + localtimezone = to_native(cpmmodule.params["timezone"]) + if cpmmodule.params["ntpenable"] is not None: + if (existing["ntp"]["enable"] != to_native(cpmmodule.params["ntpenable"])): + total_change = (total_change | 16) + localenable = to_native(cpmmodule.params["ntpenable"]) + if cpmmodule.params["ipv4address"] is not None: + loopcounter = 0 + portspassed = cpmmodule.params["ipv4address"].split(",") + for val in portspassed: + if (loopcounter == 0): + if (existing["ntp"]["ietf-ipv4"]["address"][0]["primary"] != to_native(val)): + total_change = (total_change | 32) + localprimary[0] = to_native(val) + loopcounter += 1 + else: + if (existing["ntp"]["ietf-ipv4"]["address"][0]["secondary"] != to_native(val)): + total_change = (total_change | 32) + localsecondary[0] = to_native(val) + loopcounter += 1 + if cpmmodule.params["ipv6address"] is not None: + loopcounter = 0 + portspassed = cpmmodule.params["ipv6address"].split(",") + for val in portspassed: + if (loopcounter == 0): + if (existing["ntp"]["ietf-ipv6"]["address"][0]["primary"] != to_native(val)): + total_change = (total_change | 64) + localprimary[1] = to_native(val) + loopcounter += 1 + else: + if (existing["ntp"]["ietf-ipv6"]["address"][0]["secondary"] != to_native(val)): + total_change = (total_change | 64) + localsecondary[1] = to_native(val) + loopcounter += 1 + if cpmmodule.params["timeout"] is not None: + if (existing["ntp"]["timeout"] != to_native(cpmmodule.params["timeout"])): + if ((int(to_native(cpmmodule.params["timeout"])) > 0) and (int(to_native(cpmmodule.params["timeout"])) <= 60)): + total_change = (total_change | 8) + localtimeout = to_native(cpmmodule.params["timeout"]) + + if (total_change > 0): + protocol = protocolchanged = 0 + ietfstring = "" + + if (localdate is not None): + ietfstring = '%s"date": "%s"' % (ietfstring, localdate) + + if (localtime is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"time": "%s"' % (ietfstring, localtime) + + if (localtimezone is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"timezone": "%s"' % (ietfstring, localtimezone) + + if ((localenable is not None) or (localtimeout is not None) or + (localprimary[0] is not None) or (localsecondary[0] is not None) or + (localprimary[1] is not None) or (localsecondary[1] is not None)): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "ntp": {' % (ietfstring) + + if (localenable is not None): + ietfstring = '%s"enable": "%s"' % (ietfstring, localenable) + + if (localtimeout is not None): + if (len(ietfstring) > 0): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s"timeout": "%s"' % (ietfstring, localtimeout) + + if ((localprimary[0] is not None) or (localsecondary[0] is not None)): + if ((localenable is not None) or (localtimeout is not None)): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "ietf-ipv4": { "address": [{' % (ietfstring) + + if (localprimary[0] is not None): + ietfstring = '%s "primary": "%s"' % (ietfstring, localprimary[0]) + + if (localsecondary[0] is not None): + if (localprimary[0] is not None): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "secondary": "%s"' % (ietfstring, localsecondary[0]) + + # end ietf-ipv4 block + ietfstring = '%s }]}' % (ietfstring) + + if ((localprimary[1] is not None) or (localsecondary[1] is not None)): + if ((localprimary[0] is not None) or (localsecondary[0] is not None) or + (localenable is not None) or (localtimeout is not None)): + ietfstring = '%s,' % (ietfstring) + + ietfstring = '%s "ietf-ipv6": { "address": [{' % (ietfstring) + + if (localprimary[1] is not None): + ietfstring = '%s "primary": "%s"' % (ietfstring, localprimary[1]) + + if (localsecondary[1] is not None): + if (localprimary[1] is not None): + ietfstring = '%s,' % (ietfstring) + ietfstring = '%s "secondary": "%s"' % (ietfstring, localsecondary[1]) + + # end ietf-ipv6 block + ietfstring = '%s }]}' % (ietfstring) + # end ntp block + ietfstring = '%s}' % (ietfstring) + + json_load = "{" + json_load = '%s%s' % (json_load, ietfstring) + json_load = '%s}' % (json_load) + else: + json_load = None + return json_load + + +def run_module(): + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + date=dict(type='str', required=False, default=None), + time=dict(type='str', required=False, default=None), + timezone=dict(type='int', required=False, default=None), + ntpenable=dict(type='int', required=False, default=None, choices=[0, 1]), + ipv4address=dict(type='str', required=False, default=None), + ipv6address=dict(type='str', required=False, default=None), + timeout=dict(type='int', required=False, default=None), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + fullurl = ("%s%s/api/v2/config/timedate" % (protocol, to_native(module.params['cpm_url']))) + method = 'GET' + try: + response = open_url(fullurl, data=None, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = response.read() + payload = assemble_json(module, json.loads(result['data'])) + + if module.check_mode: + if payload is not None: + result['changed'] = True + else: + if payload is not None: + fullurl = ("%s%s/api/v2/config/timedate" % (protocol, to_native(module.params['cpm_url']))) + method = 'POST' + + try: + response = open_url(fullurl, data=payload, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='POST: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='POST: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='POST: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='POST: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['changed'] = True + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_time_info.py b/ansible_collections/wti/remote/plugins/modules/cpm_time_info.py new file mode 100644 index 00000000..8b8409dd --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_time_info.py @@ -0,0 +1,190 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2019 Red Hat Inc. +# Copyright (C) 2019 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to retrieve WTI time date Parameters from WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_time_info +version_added: "2.10.0" +author: + - "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get Time/Date parameters in WTI OOB and PDU devices +description: + - "Get Time/Date and NTP parameters from WTI OOB and PDU devices" +options: + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + type: bool + required: false + default: true + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: + - Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false +notes: + - Use C(groups/cpm) in C(module_defaults) to set common options used between CPM modules.) +""" + +EXAMPLES = """ +- name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: true + validate_certs: false + +- name: Get the Time/Date Parameters for a WTI device + cpm_time_info: + cpm_url: "nonexist.wti.com" + cpm_username: "super" + cpm_password: "super" + use_https: false + validate_certs: false +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: complex + contains: + date: + description: Current Date of the WTI device after module execution. + returned: success + type: str + sample: "11/14/2019" + time: + description: Current Time of the WTI device after module execution. + returned: success + type: str + sample: "12:12:00" + timezone: + description: Current Timezone of the WTI device after module execution. + returned: success + type: int + sample: 5 + ntp: + description: Current k/v pairs of ntp info of the WTI device after module execution. + returned: always + type: dict + sample: {"enable": "0", + "ietf-ipv4": {"address": [{"primary": "192.168.0.169","secondary": "12.34.56.78"}]}, + "ietf-ipv6": {"address": [{"primary": "","secondary": ""}]}, + "timeout": "4"} +""" + +import base64 +import json + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def run_module(): + # define the available arguments/parameters that a user can pass to + # the module + module_args = dict( + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True), + cpm_password=dict(type='str', required=True, no_log=True), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + fullurl = ("%s%s/api/v2/config/timedate" % (protocol, to_native(module.params['cpm_url']))) + + try: + response = open_url(fullurl, data=None, method='GET', validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + + except HTTPError as e: + fail_json = dict(msg='GET: Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='GET: Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='GET: Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='GET: Error connecting to {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = json.loads(response.read()) + + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/plugins/modules/cpm_user.py b/ansible_collections/wti/remote/plugins/modules/cpm_user.py new file mode 100644 index 00000000..ffab07f1 --- /dev/null +++ b/ansible_collections/wti/remote/plugins/modules/cpm_user.py @@ -0,0 +1,355 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +# (C) 2018 Red Hat Inc. +# Copyright (C) 2018 Western Telematic Inc. +# +# GNU General Public License v3.0+ +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +# +# Module to execute CPM User Commands on WTI OOB and PDU devices. +# CPM remote_management +# +from __future__ import absolute_import, division, print_function +__metaclass__ = type + +ANSIBLE_METADATA = { + 'metadata_version': '1.1', + 'status': ['preview'], + 'supported_by': 'community' +} + +DOCUMENTATION = """ +--- +module: cpm_user +version_added: "2.7.0" +author: "Western Telematic Inc. (@wtinetworkgear)" +short_description: Get various status and parameters from WTI OOB and PDU devices +description: + - "Get/Add/Edit Delete Users from WTI OOB and PDU devices" +options: + cpm_action: + description: + - This is the Action to send the module. + required: true + type: str + choices: [ "getuser", "adduser", "edituser", "deleteuser" ] + cpm_url: + description: + - This is the URL of the WTI device to send the module. + type: str + required: true + cpm_username: + description: + - This is the Basic Authentication Username of the WTI device to send the module. + type: str + required: true + cpm_password: + description: + - This is the Basic Authentication Password of the WTI device to send the module. + type: str + required: true + use_https: + description: + - Designates to use an https connection or http connection. + required: false + default: true + type: bool + validate_certs: + description: + - If false, SSL certificates will not be validated. This should only be used + - on personally controlled sites using self-signed certificates. + type: bool + required: false + default: true + use_proxy: + description: Flag to control if the lookup will observe HTTP proxy environment variables when present. + type: bool + required: false + default: false + user_name: + description: + - This is the User Name that needs to be create/modified/deleted + type: str + required: true + user_pass: + description: + - This is the User Password that needs to be create/modified/deleted + - If the user is being Created this parameter is required + type: str + required: false + user_accesslevel: + description: + - This is the access level that needs to be create/modified/deleted + - 0 View, 1 User, 2 SuperUser, 3 Administrator + type: int + required: false + choices: [ 0, 1, 2, 3 ] + user_accessssh: + description: + - If the user has access to the WTI device via SSH + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessserial: + description: + - If the user has access to the WTI device via Serial ports + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessweb: + description: + - If the user has access to the WTI device via Web + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessapi: + description: + - If the user has access to the WTI device via RESTful APIs + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessmonitor: + description: + - If the user has ability to monitor connection sessions + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_accessoutbound: + description: + - If the user has ability to initiate Outbound connection + - 0 No , 1 Yes + type: int + required: false + choices: [ 0, 1 ] + user_portaccess: + description: + - If AccessLevel is lower than Administrator, which ports the user has access + type: str + required: false + user_plugaccess: + description: + - If AccessLevel is lower than Administrator, which plugs the user has access + type: str + required: false + user_groupaccess: + description: + - If AccessLevel is lower than Administrator, which Groups the user has access + type: str + required: false + user_callbackphone: + description: + - This is the Call Back phone number used for POTS modem connections + type: str + required: false + """ + +EXAMPLES = """ +# Get User Parameters +- name: Get the User Parameters for the given user of a WTI device + cpm_user: + cpm_action: "getuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" + +# Create User +- name: Create a User on a given WTI device + cpm_user: + cpm_action: "adduser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "complicatedpassword" + user_accesslevel: 2 + user_accessssh: 1 + user_accessserial: 1 + user_accessweb: 0 + user_accessapi: 1 + user_accessmonitor: 0 + user_accessoutbound: 0 + user_portaccess: "10011111" + user_plugaccess: "00000111" + user_groupaccess: "00000000" + +# Edit User +- name: Edit a User on a given WTI device + cpm_user: + cpm_action: "edituser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: false + user_name: "usernumberone" + user_pass: "newpasswordcomplicatedpassword" + +# Delete User +- name: Delete a User from a given WTI device + cpm_user: + cpm_action: "deleteuser" + cpm_url: "rest.wti.com" + cpm_username: "restuser" + cpm_password: "restfuluserpass12" + use_https: true + validate_certs: true + user_name: "usernumberone" +""" + +RETURN = """ +data: + description: The output JSON returned from the commands sent + returned: always + type: str +""" + +import base64 + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils._text import to_text, to_bytes, to_native +from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError +from ansible.module_utils.urls import open_url, ConnectionError, SSLValidationError + + +def assemble_json(cpmmodule): + json_load = '{"users":{"username": "%s"' % to_native((cpmmodule.params["user_name"])) + + # for Adding there must be a password present + if cpmmodule.params["user_pass"] is not None and (len(cpmmodule.params["user_pass"]) > 0): + json_load = '%s,"newpasswd": "%s"' % (json_load, to_native(cpmmodule.params["user_pass"])) + if cpmmodule.params["user_accesslevel"] is not None: + json_load = '%s,"accesslevel": %s' % (json_load, to_native(cpmmodule.params["user_accesslevel"])) + if cpmmodule.params["user_portaccess"] is not None: + json_load = '%s,"portaccess": %s' % (json_load, to_native(cpmmodule.params["user_portaccess"])) + if cpmmodule.params["user_plugaccess"] is not None: + json_load = '%s,"plugaccess": %s' % (json_load, to_native(cpmmodule.params["user_plugaccess"])) + if cpmmodule.params["user_groupaccess"] is not None: + json_load = '%s,"groupaccess": %s' % (json_load, to_native(cpmmodule.params["user_groupaccess"])) + if cpmmodule.params["user_accessserial"] is not None: + json_load = '%s,"accessserial": %s' % (json_load, to_native(cpmmodule.params["user_accessserial"])) + if cpmmodule.params["user_accessssh"] is not None: + json_load = '%s,"accessssh": %s' % (json_load, to_native(cpmmodule.params["user_accessssh"])) + if cpmmodule.params["user_accessweb"] is not None: + json_load = '%s,"accessweb": %s' % (json_load, to_native(cpmmodule.params["user_accessweb"])) + if cpmmodule.params["user_accessoutbound"] is not None: + json_load = '%s,"accessoutbound": %s' % (json_load, to_native(cpmmodule.params["user_accessoutbound"])) + if cpmmodule.params["user_accessapi"] is not None: + json_load = '%s,"accessapi": %s' % (json_load, to_native(cpmmodule.params["user_accessapi"])) + if cpmmodule.params["user_accessmonitor"] is not None: + json_load = '%s,"accessmonitor": %s' % (json_load, to_native(cpmmodule.params["user_accessmonitor"])) + if cpmmodule.params["user_callbackphone"] is not None: + json_load = '%s,"callbackphone": "%s"' % (json_load, to_native(cpmmodule.params["user_callbackphone"])) + + json_load = '%s}}' % (json_load) + + return json_load + + +def run_module(): + + module_args = dict( + cpm_action=dict(choices=['getuser', 'adduser', 'edituser', 'deleteuser'], required=True), + cpm_url=dict(type='str', required=True), + cpm_username=dict(type='str', required=True, no_log=False), + cpm_password=dict(type='str', required=True, no_log=True), + user_name=dict(type='str', required=True), + user_pass=dict(type='str', required=False, default=None, no_log=True), + user_accesslevel=dict(type='int', required=False, default=None, choices=[0, 1, 2, 3]), + user_accessssh=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessserial=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessweb=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessapi=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessmonitor=dict(type='int', required=False, default=None, choices=[0, 1]), + user_accessoutbound=dict(type='int', required=False, default=None, choices=[0, 1]), + user_portaccess=dict(type='str', required=False, default=None), + user_plugaccess=dict(type='str', required=False, default=None), + user_groupaccess=dict(type='str', required=False, default=None), + user_callbackphone=dict(type='str', required=False, default=None), + use_https=dict(type='bool', default=True), + validate_certs=dict(type='bool', default=True), + use_proxy=dict(type='bool', default=False) + ) + + result = dict( + changed=False, + data='' + ) + + module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) + + if module.check_mode: + return result + + auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(to_native(module.params['cpm_username']), to_native(module.params['cpm_password'])), + errors='surrogate_or_strict'))) + + if module.params['use_https'] is True: + protocol = "https://" + else: + protocol = "http://" + + payload = None + if (module.params['cpm_action'] == 'getuser'): + fullurl = ("%s%s/api/v2/config/users?username=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['user_name']))) + method = 'GET' + elif (module.params['cpm_action'] == 'adduser'): + if module.params["user_pass"] is None or (len(module.params["user_pass"]) == 0): + module.fail_json(msg='user_pass not defined.', **result) + + payload = assemble_json(module) + fullurl = ("%s%s/api/v2/config/users" % (protocol, to_native(module.params['cpm_url']))) + method = 'POST' + elif (module.params['cpm_action'] == 'edituser'): + payload = assemble_json(module) + fullurl = ("%s%s/api/v2/config/users" % (protocol, to_native(module.params['cpm_url']))) + method = 'PUT' + elif (module.params['cpm_action'] == 'deleteuser'): + fullurl = ("%s%s/api/v2/config/users?username=%s" % (protocol, to_native(module.params['cpm_url']), to_native(module.params['user_name']))) + method = 'DELETE' + + try: + response = open_url(fullurl, data=payload, method=method, validate_certs=module.params['validate_certs'], use_proxy=module.params['use_proxy'], + headers={'Content-Type': 'application/json', 'Authorization': "Basic %s" % auth}) + if (method != 'GET'): + result['changed'] = True + + except HTTPError as e: + fail_json = dict(msg='Received HTTP error for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except URLError as e: + fail_json = dict(msg='Failed lookup url for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except SSLValidationError as e: + fail_json = dict(msg='Error validating the server''s certificate for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + except ConnectionError as e: + fail_json = dict(msg='Error connecting to for {0} : {1}'.format(fullurl, to_native(e)), changed=False) + module.fail_json(**fail_json) + + result['data'] = to_text(response.read()) + module.exit_json(**result) + + +def main(): + run_module() + + +if __name__ == '__main__': + main() diff --git a/ansible_collections/wti/remote/requirements-wti.txt b/ansible_collections/wti/remote/requirements-wti.txt new file mode 100644 index 00000000..c1d34ae8 --- /dev/null +++ b/ansible_collections/wti/remote/requirements-wti.txt @@ -0,0 +1 @@ +requests[security] |