1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Auto Commit for: fmgr_device_group (#52784)

This commit is contained in:
ftntcorecse 2019-02-27 01:49:18 -05:00 committed by Nilashish Chakraborty
parent 2efacfcdad
commit b1f117ec99
3 changed files with 406 additions and 516 deletions

View file

@ -29,6 +29,8 @@ DOCUMENTATION = '''
--- ---
module: fmgr_device_group module: fmgr_device_group
version_added: "2.8" version_added: "2.8"
notes:
- Full Documentation at U(https://ftnt-ansible-docs.readthedocs.io/en/latest/).
author: author:
- Luke Weighall (@lweighall) - Luke Weighall (@lweighall)
- Andrew Welsh (@Ghilli3) - Andrew Welsh (@Ghilli3)
@ -50,21 +52,6 @@ options:
required: false required: false
default: root default: root
host:
description:
- The FortiManager's address.
required: true
username:
description:
- The username to log into the FortiManager.
required: true
password:
description:
- The password associated with the username account.
required: false
mode: mode:
description: description:
- Sets one of three modes for managing the object. - Sets one of three modes for managing the object.
@ -96,9 +83,6 @@ options:
EXAMPLES = ''' EXAMPLES = '''
- name: CREATE DEVICE GROUP - name: CREATE DEVICE GROUP
fmgr_device_group: fmgr_device_group:
host: "{{inventory_hostname}}"
username: "{{ username }}"
password: "{{ password }}"
grp_name: "TestGroup" grp_name: "TestGroup"
grp_desc: "CreatedbyAnsible" grp_desc: "CreatedbyAnsible"
adom: "ansible" adom: "ansible"
@ -106,9 +90,6 @@ EXAMPLES = '''
- name: CREATE DEVICE GROUP 2 - name: CREATE DEVICE GROUP 2
fmgr_device_group: fmgr_device_group:
host: "{{inventory_hostname}}"
username: "{{ username }}"
password: "{{ password }}"
grp_name: "AnsibleGroup" grp_name: "AnsibleGroup"
grp_desc: "CreatedbyAnsible" grp_desc: "CreatedbyAnsible"
adom: "ansible" adom: "ansible"
@ -116,9 +97,6 @@ EXAMPLES = '''
- name: ADD DEVICES TO DEVICE GROUP - name: ADD DEVICES TO DEVICE GROUP
fmgr_device_group: fmgr_device_group:
host: "{{inventory_hostname}}"
username: "{{ username }}"
password: "{{ password }}"
mode: "add" mode: "add"
grp_name: "TestGroup" grp_name: "TestGroup"
grp_members: "FGT1,FGT2" grp_members: "FGT1,FGT2"
@ -127,9 +105,6 @@ EXAMPLES = '''
- name: REMOVE DEVICES TO DEVICE GROUP - name: REMOVE DEVICES TO DEVICE GROUP
fmgr_device_group: fmgr_device_group:
host: "{{inventory_hostname}}"
username: "{{ username }}"
password: "{{ password }}"
mode: "delete" mode: "delete"
grp_name: "TestGroup" grp_name: "TestGroup"
grp_members: "FGT1,FGT2" grp_members: "FGT1,FGT2"
@ -137,9 +112,6 @@ EXAMPLES = '''
- name: DELETE DEVICE GROUP - name: DELETE DEVICE GROUP
fmgr_device_group: fmgr_device_group:
host: "{{inventory_hostname}}"
username: "{{ username }}"
password: "{{ password }}"
grp_name: "AnsibleGroup" grp_name: "AnsibleGroup"
grp_desc: "CreatedbyAnsible" grp_desc: "CreatedbyAnsible"
mode: "delete" mode: "delete"
@ -154,20 +126,23 @@ api_result:
""" """
from ansible.module_utils.basic import AnsibleModule, env_fallback from ansible.module_utils.basic import AnsibleModule, env_fallback
from ansible.module_utils.network.fortimanager.fortimanager import AnsibleFortiManager from ansible.module_utils.connection import Connection
from ansible.module_utils.network.fortimanager.fortimanager import FortiManagerHandler
from ansible.module_utils.network.fortimanager.common import FMGBaseException
from ansible.module_utils.network.fortimanager.common import FMGRCommon
from ansible.module_utils.network.fortimanager.common import FMGRMethods
from ansible.module_utils.network.fortimanager.common import DEFAULT_RESULT_OBJ
from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
# check for pyFMG lib def get_groups(fmgr, paramgram):
try:
from pyFMG.fortimgr import FortiManager
HAS_PYFMGR = True
except ImportError:
HAS_PYFMGR = False
def get_groups(fmg, paramgram):
""" """
This method is used GET the HA PEERS of a FortiManager Node :param fmgr: The fmgr object instance from fortimanager.py
:type fmgr: class object
:param paramgram: The formatted dictionary of options to process
:type paramgram: dict
:return: The response from the FortiManager
:rtype: dict
""" """
datagram = { datagram = {
@ -175,16 +150,21 @@ def get_groups(fmg, paramgram):
} }
url = '/dvmdb/adom/{adom}/group'.format(adom=paramgram["adom"]) url = '/dvmdb/adom/{adom}/group'.format(adom=paramgram["adom"])
response = fmg.get(url, datagram) response = fmgr.process_request(url, datagram, FMGRMethods.GET)
return response return response
def add_device_group(fmg, paramgram): def add_device_group(fmgr, paramgram):
""" """
This method is used to add device groups :param fmgr: The fmgr object instance from fortimanager.py
:type fmgr: class object
:param paramgram: The formatted dictionary of options to process
:type paramgram: dict
:return: The response from the FortiManager
:rtype: dict
""" """
# INIT A BASIC OBJECTS # INIT A BASIC OBJECTS
response = (-100000, {"msg": "Illegal or malformed paramgram discovered. System Exception"}) response = DEFAULT_RESULT_OBJ
url = "" url = ""
mode = paramgram["mode"] mode = paramgram["mode"]
@ -198,23 +178,28 @@ def add_device_group(fmg, paramgram):
# IF MODE = SET -- USE THE 'SET' API CALL MODE # IF MODE = SET -- USE THE 'SET' API CALL MODE
if mode == "set": if mode == "set":
response = fmg.set(url, datagram) response = fmgr.process_request(url, datagram, FMGRMethods.SET)
# IF MODE = UPDATE -- USER THE 'UPDATE' API CALL MODE # IF MODE = UPDATE -- USER THE 'UPDATE' API CALL MODE
elif mode == "update": elif mode == "update":
response = fmg.update(url, datagram) response = fmgr.process_request(url, datagram, FMGRMethods.UPDATE)
# IF MODE = ADD -- USE THE 'ADD' API CALL MODE # IF MODE = ADD -- USE THE 'ADD' API CALL MODE
elif mode == "add": elif mode == "add":
response = fmg.add(url, datagram) response = fmgr.process_request(url, datagram, FMGRMethods.ADD)
return response return response
def delete_device_group(fmg, paramgram): def delete_device_group(fmgr, paramgram):
""" """
This method is used to add devices to the FMGR :param fmgr: The fmgr object instance from fortimanager.py
:type fmgr: class object
:param paramgram: The formatted dictionary of options to process
:type paramgram: dict
:return: The response from the FortiManager
:rtype: dict
""" """
# INIT A BASIC OBJECTS # INIT A BASIC OBJECTS
response = (-100000, {"msg": "Illegal or malformed paramgram discovered. System Exception"}) response = DEFAULT_RESULT_OBJ
url = "" url = ""
datagram = { datagram = {
@ -223,16 +208,21 @@ def delete_device_group(fmg, paramgram):
} }
url = '/dvmdb/adom/{adom}/group/{grp_name}'.format(adom=paramgram["adom"], grp_name=paramgram["grp_name"]) url = '/dvmdb/adom/{adom}/group/{grp_name}'.format(adom=paramgram["adom"], grp_name=paramgram["grp_name"])
response = fmg.delete(url, datagram) response = fmgr.process_request(url, datagram, FMGRMethods.DELETE)
return response return response
def add_group_member(fmg, paramgram): def add_group_member(fmgr, paramgram):
""" """
This method is used to update device groups add members :param fmgr: The fmgr object instance from fortimanager.py
:type fmgr: class object
:param paramgram: The formatted dictionary of options to process
:type paramgram: dict
:return: The response from the FortiManager
:rtype: dict
""" """
# INIT A BASIC OBJECTS # INIT A BASIC OBJECTS
response = (-100000, {"msg": "Illegal or malformed paramgram discovered. System Exception"}) response = DEFAULT_RESULT_OBJ
url = "" url = ""
device_member_list = paramgram["grp_members"].replace(' ', '') device_member_list = paramgram["grp_members"].replace(' ', '')
device_member_list = device_member_list.split(',') device_member_list = device_member_list.split(',')
@ -242,17 +232,22 @@ def add_group_member(fmg, paramgram):
url = '/dvmdb/adom/{adom}/group/{grp_name}/object member'.format(adom=paramgram["adom"], url = '/dvmdb/adom/{adom}/group/{grp_name}/object member'.format(adom=paramgram["adom"],
grp_name=paramgram["grp_name"]) grp_name=paramgram["grp_name"])
response = fmg.add(url, datagram) response = fmgr.process_request(url, datagram, FMGRMethods.ADD)
return response return response
def delete_group_member(fmg, paramgram): def delete_group_member(fmgr, paramgram):
""" """
This method is used to update device groups add members :param fmgr: The fmgr object instance from fortimanager.py
:type fmgr: class object
:param paramgram: The formatted dictionary of options to process
:type paramgram: dict
:return: The response from the FortiManager
:rtype: dict
""" """
# INIT A BASIC OBJECTS # INIT A BASIC OBJECTS
response = (-100000, {"msg": "Illegal or malformed paramgram discovered. System Exception"}) response = DEFAULT_RESULT_OBJ
url = "" url = ""
device_member_list = paramgram["grp_members"].replace(' ', '') device_member_list = paramgram["grp_members"].replace(' ', '')
device_member_list = device_member_list.split(',') device_member_list = device_member_list.split(',')
@ -262,65 +257,22 @@ def delete_group_member(fmg, paramgram):
url = '/dvmdb/adom/{adom}/group/{grp_name}/object member'.format(adom=paramgram["adom"], url = '/dvmdb/adom/{adom}/group/{grp_name}/object member'.format(adom=paramgram["adom"],
grp_name=paramgram["grp_name"]) grp_name=paramgram["grp_name"])
response = fmg.delete(url, datagram) response = fmgr.process_request(url, datagram, FMGRMethods.DELETE)
return response return response
# FUNCTION/METHOD FOR LOGGING OUT AND ANALYZING ERROR CODES
def fmgr_logout(fmg, module, msg="NULL", results=(), good_codes=(0,), logout_on_fail=True, logout_on_success=False):
"""
THIS METHOD CONTROLS THE LOGOUT AND ERROR REPORTING AFTER AN METHOD OR FUNCTION RUNS
"""
# VALIDATION ERROR (NO RESULTS, JUST AN EXIT)
if msg != "NULL" and len(results) == 0:
try:
fmg.logout()
except Exception:
pass
module.fail_json(msg=msg)
# SUBMISSION ERROR
if len(results) > 0:
if msg == "NULL":
try:
msg = results[1]['status']['message']
except Exception:
msg = "No status message returned from pyFMG. Possible that this was a GET with a tuple result."
if results[0] not in good_codes:
if logout_on_fail:
fmg.logout()
module.fail_json(msg=msg, **results[1])
else:
return_msg = msg + " -- LOGOUT ON FAIL IS OFF, MOVING ON"
return return_msg
else:
if logout_on_success:
fmg.logout()
module.exit_json(msg=msg, **results[1])
else:
return_msg = msg + " -- LOGOUT ON SUCCESS IS OFF, MOVING ON TO REST OF CODE"
return return_msg
def main(): def main():
argument_spec = dict( argument_spec = dict(
adom=dict(required=False, type="str", default="root"), adom=dict(required=False, type="str", default="root"),
vdom=dict(required=False, type="str", default="root"), vdom=dict(required=False, type="str", default="root"),
host=dict(required=True, type="str"),
username=dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])),
password=dict(fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True),
mode=dict(choices=["add", "set", "delete", "update"], type="str", default="add"), mode=dict(choices=["add", "set", "delete", "update"], type="str", default="add"),
grp_desc=dict(required=False, type="str"), grp_desc=dict(required=False, type="str"),
grp_name=dict(required=True, type="str"), grp_name=dict(required=True, type="str"),
grp_members=dict(required=False, type="str"), grp_members=dict(required=False, type="str"),
) )
module = AnsibleModule(argument_spec, supports_check_mode=True, ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, )
# handle params passed via provider and insure they are represented as the data type expected by fortimanager
paramgram = { paramgram = {
"mode": module.params["mode"], "mode": module.params["mode"],
"grp_name": module.params["grp_name"], "grp_name": module.params["grp_name"],
@ -329,49 +281,48 @@ def main():
"adom": module.params["adom"], "adom": module.params["adom"],
"vdom": module.params["vdom"] "vdom": module.params["vdom"]
} }
module.paramgram = paramgram
# validate required arguments are passed; not used in argument_spec to allow params to be called from provider fmgr = None
# check if params are set if module._socket_path:
if module.params["host"] is None or module.params["username"] is None or module.params["password"] is None: connection = Connection(module._socket_path)
module.fail_json(msg="Host and username are required for connection") fmgr = FortiManagerHandler(connection, module)
fmgr.tools = FMGRCommon()
# CHECK IF LOGIN FAILED
fmg = AnsibleFortiManager(module, module.params["host"], module.params["username"], module.params["password"])
response = fmg.login()
if response[1]['status']['code'] != 0:
module.fail_json(msg="Connection to FortiManager Failed")
else: else:
# START SESSION LOGIC module.fail_json(**FAIL_SOCKET_MSG)
# BEGIN MODULE-SPECIFIC LOGIC -- THINGS NEED TO HAPPEN DEPENDING ON THE ENDPOINT AND OPERATION
results = DEFAULT_RESULT_OBJ
try:
# PROCESS THE GROUP ADDS FIRST # PROCESS THE GROUP ADDS FIRST
if paramgram["grp_name"] is not None and paramgram["mode"] in ["add", "set", "update"]: if paramgram["grp_name"] is not None and paramgram["mode"] in ["add", "set", "update"]:
# add device group # add device group
results = add_device_group(fmg, paramgram) results = add_device_group(fmgr, paramgram)
if results[0] != 0 and results[0] != -2: fmgr.govern_response(module=module, results=results,
fmgr_logout(fmg, module, msg="Failed to Add Device Group", results=results, good_codes=[0]) ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
# PROCESS THE GROUP MEMBER ADDS # PROCESS THE GROUP MEMBER ADDS
if paramgram["grp_members"] is not None and paramgram["mode"] in ["add", "set", "update"]: if paramgram["grp_members"] is not None and paramgram["mode"] in ["add", "set", "update"]:
# assign devices to device group # assign devices to device group
results = add_group_member(fmg, paramgram) results = add_group_member(fmgr, paramgram)
if results[0] != 0 and results[0] != -2: fmgr.govern_response(module=module, results=results,
fmgr_logout(fmg, module, msg="Failed to Add Group Member(s)", results=results, good_codes=[0]) ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
# PROCESS THE GROUP MEMBER DELETES # PROCESS THE GROUP MEMBER DELETES
if paramgram["grp_members"] is not None and paramgram["mode"] == "delete": if paramgram["grp_members"] is not None and paramgram["mode"] == "delete":
# remove devices grom a group # remove devices grom a group
results = delete_group_member(fmg, paramgram) results = delete_group_member(fmgr, paramgram)
if results[0] != 0: fmgr.govern_response(module=module, results=results,
fmgr_logout(fmg, module, msg="Failed to Delete Group Member(s)", results=results, good_codes=[0]) ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
# PROCESS THE GROUP DELETES, ONLY IF GRP_MEMBERS IS NOT NULL TOO # PROCESS THE GROUP DELETES, ONLY IF GRP_MEMBERS IS NOT NULL TOO
if paramgram["grp_name"] is not None and paramgram["mode"] == "delete" and paramgram["grp_members"] is None: if paramgram["grp_name"] is not None and paramgram["mode"] == "delete" and paramgram["grp_members"] is None:
# delete device group # delete device group
results = delete_device_group(fmg, paramgram) results = delete_device_group(fmgr, paramgram)
if results[0] != 0: fmgr.govern_response(module=module, results=results,
fmgr_logout(fmg, module, msg="Failed to Delete Device Group", results=results, good_codes=[0]) ansible_facts=fmgr.construct_ansible_facts(results, module.params, paramgram))
except Exception as err:
raise FMGBaseException(err)
# RETURN THE RESULTS
return module.exit_json(**results[1]) return module.exit_json(**results[1])

View file

@ -1,226 +1,234 @@
{ {
"add_group_member": [ "add_group_member": [
{ {
"raw_response": { "raw_response": {
"status": { "status": {
"message": "OK", "message": "OK",
"code": 0 "code": 0
}, },
"url": "/dvmdb/adom/ansible/group/TestGroup/object member" "url": "/dvmdb/adom/ansible/group/TestGroup/object member"
}, },
"paramgram_used": { "datagram_sent": {
"grp_desc": null, "name": "FGT1",
"adom": "ansible", "vdom": "root"
"grp_members": "FGT1,FGT2", },
"state": "present", "paramgram_used": {
"grp_name": "TestGroup", "grp_desc": null,
"vdom": "root" "adom": "ansible",
}, "grp_members": "FGT1",
"post_method": "add" "mode": "add",
}, "grp_name": "TestGroup",
{ "vdom": "root"
"paramgram_used": { },
"grp_desc": null, "post_method": "add"
"adom": "ansible", },
"grp_members": "FGT1,FGT2", {
"state": "present", "raw_response": {
"grp_name": "TestGroup", "status": {
"vdom": "root" "message": "OK",
}, "code": 0
"raw_response": { },
"status": { "url": "/dvmdb/adom/ansible/group/testtest/object member"
"message": "OK", },
"code": 0 "datagram_sent": {
}, "name": "FGT3",
"url": "/dvmdb/adom/ansible/group/TestGroup/object member" "vdom": "root"
}, },
"post_method": "add" "paramgram_used": {
}, "grp_desc": null,
{ "adom": "ansible",
"paramgram_used": { "grp_members": "FGT3",
"grp_desc": null, "mode": "add",
"adom": "ansible", "grp_name": "testtest",
"grp_members": "FGT3", "vdom": "root"
"state": "present", },
"grp_name": "testtest", "post_method": "add"
"vdom": "root" }
}, ],
"raw_response": { "delete_device_group": [
"status": { {
"message": "OK", "paramgram_used": {
"code": 0 "grp_desc": "CreatedbyAnsible",
}, "adom": "ansible",
"url": "/dvmdb/adom/ansible/group/testtest/object member" "grp_members": null,
}, "mode": "delete",
"post_method": "add" "grp_name": "TestGroup",
} "vdom": "root"
], },
"delete_device_group": [ "datagram_sent": {
{ "name": "TestGroup",
"paramgram_used": { "adom": "ansible"
"grp_desc": "CreatedbyAnsible", },
"adom": "ansible", "raw_response": {
"grp_members": null, "status": {
"state": "absent", "message": "OK",
"grp_name": "TestGroup", "code": 0
"vdom": "root" },
}, "url": "/dvmdb/adom/ansible/group/TestGroup"
"raw_response": { },
"status": { "post_method": "delete"
"message": "OK", },
"code": 0 {
}, "raw_response": {
"url": "/dvmdb/adom/ansible/group/TestGroup" "status": {
}, "message": "OK",
"post_method": "delete" "code": 0
}, },
{ "url": "/dvmdb/adom/ansible/group/testtest"
"raw_response": { },
"status": { "datagram_sent": {
"message": "OK", "name": "testtest",
"code": 0 "adom": "ansible"
}, },
"url": "/dvmdb/adom/ansible/group/testtest" "paramgram_used": {
}, "grp_desc": "CreatedbyAnsible",
"paramgram_used": { "adom": "ansible",
"grp_desc": "CreatedbyAnsible", "grp_members": null,
"adom": "ansible", "mode": "delete",
"grp_members": null, "grp_name": "testtest",
"state": "absent", "vdom": "root"
"grp_name": "testtest", },
"vdom": "root" "post_method": "delete"
}, }
"post_method": "delete" ],
} "add_device_group": [
], {
"add_device_group": [ "paramgram_used": {
{ "grp_desc": "CreatedbyAnsible",
"paramgram_used": { "adom": "ansible",
"grp_desc": "CreatedbyAnsible", "grp_members": null,
"adom": "ansible", "mode": "add",
"grp_members": null, "grp_name": "TestGroup",
"state": "present", "vdom": "root"
"grp_name": "TestGroup", },
"vdom": "root" "datagram_sent": {
}, "os_type": "fos",
"raw_response": { "name": "TestGroup",
"status": { "desc": "CreatedbyAnsible"
"message": "OK", },
"code": 0 "raw_response": {
}, "status": {
"url": "/dvmdb/adom/ansible/group" "message": "Object already exists",
}, "code": -2
"post_method": "add" },
}, "url": "/dvmdb/adom/ansible/group"
{ },
"raw_response": { "post_method": "add"
"status": { },
"message": "OK", {
"code": 0 "raw_response": {
}, "status": {
"url": "/dvmdb/adom/ansible/group" "message": "OK",
}, "code": 0
"paramgram_used": { },
"grp_desc": "CreatedbyAnsible", "url": "/dvmdb/adom/ansible/group"
"adom": "ansible", },
"grp_members": null, "datagram_sent": {
"state": "present", "os_type": "fos",
"grp_name": "testtest", "name": "testtest",
"vdom": "root" "desc": "CreatedbyAnsible"
}, },
"post_method": "add" "paramgram_used": {
}, "grp_desc": "CreatedbyAnsible",
{ "adom": "ansible",
"paramgram_used": { "grp_members": null,
"grp_desc": null, "mode": "add",
"adom": "ansible", "grp_name": "testtest",
"grp_members": "FGT1,FGT2", "vdom": "root"
"state": "present", },
"grp_name": "TestGroup", "post_method": "add"
"vdom": "root" },
}, {
"raw_response": { "paramgram_used": {
"status": { "grp_desc": null,
"message": "Object already exists", "adom": "ansible",
"code": -2 "grp_members": "FGT1",
}, "mode": "add",
"url": "/dvmdb/adom/ansible/group" "grp_name": "TestGroup",
}, "vdom": "root"
"post_method": "add" },
}, "datagram_sent": {
{ "os_type": "fos",
"raw_response": { "name": "TestGroup",
"status": { "desc": null
"message": "Object already exists", },
"code": -2 "raw_response": {
}, "status": {
"url": "/dvmdb/adom/ansible/group" "message": "Object already exists",
}, "code": -2
"paramgram_used": { },
"grp_desc": null, "url": "/dvmdb/adom/ansible/group"
"adom": "ansible", },
"grp_members": "FGT3", "post_method": "add"
"state": "present", },
"grp_name": "testtest", {
"vdom": "root" "paramgram_used": {
}, "grp_desc": null,
"post_method": "add" "adom": "ansible",
} "grp_members": "FGT3",
], "mode": "add",
"delete_group_member": [ "grp_name": "testtest",
{ "vdom": "root"
"raw_response": { },
"status": { "datagram_sent": {
"message": "OK", "os_type": "fos",
"code": 0 "name": "testtest",
}, "desc": null
"url": "/dvmdb/adom/ansible/group/testtest/object member" },
}, "raw_response": {
"paramgram_used": { "status": {
"grp_desc": null, "message": "Object already exists",
"adom": "ansible", "code": -2
"grp_members": "FGT3", },
"state": "absent", "url": "/dvmdb/adom/ansible/group"
"grp_name": "testtest", },
"vdom": "root" "post_method": "add"
}, }
"post_method": "delete" ],
}, "delete_group_member": [
{ {
"paramgram_used": { "paramgram_used": {
"grp_desc": null, "grp_desc": null,
"adom": "ansible", "adom": "ansible",
"grp_members": "FGT1,FGT2", "grp_members": "FGT3",
"state": "absent", "mode": "delete",
"grp_name": "TestGroup", "grp_name": "testtest",
"vdom": "root" "vdom": "root"
}, },
"raw_response": { "datagram_sent": {
"status": { "name": "FGT3",
"message": "OK", "vdom": "root"
"code": 0 },
}, "raw_response": {
"url": "/dvmdb/adom/ansible/group/TestGroup/object member" "status": {
}, "message": "OK",
"post_method": "delete" "code": 0
}, },
{ "url": "/dvmdb/adom/ansible/group/testtest/object member"
"raw_response": { },
"status": { "post_method": "delete"
"message": "OK", },
"code": 0 {
}, "raw_response": {
"url": "/dvmdb/adom/ansible/group/TestGroup/object member" "status": {
}, "message": "OK",
"paramgram_used": { "code": 0
"grp_desc": null, },
"adom": "ansible", "url": "/dvmdb/adom/ansible/group/TestGroup/object member"
"grp_members": "FGT1,FGT2", },
"state": "absent", "datagram_sent": {
"grp_name": "TestGroup", "name": "FGT1",
"vdom": "root" "vdom": "root"
}, },
"post_method": "delete" "paramgram_used": {
} "grp_desc": null,
] "adom": "ansible",
"grp_members": "FGT1",
"mode": "delete",
"grp_name": "TestGroup",
"vdom": "root"
},
"post_method": "delete"
}
]
} }

View file

@ -19,17 +19,13 @@ __metaclass__ = type
import os import os
import json import json
from pyFMG.fortimgr import FortiManager from ansible.module_utils.network.fortimanager.fortimanager import FortiManagerHandler
import pytest import pytest
try: try:
from ansible.modules.network.fortimanager import fmgr_device_group from ansible.modules.network.fortimanager import fmgr_device_group
except ImportError: except ImportError:
pytest.skip( pytest.skip("Could not load required modules for testing", allow_module_level=True)
"Could not load required modules for testing",
allow_module_level=True)
fmg_instance = FortiManager("1.1.1.1", "admin", "")
def load_fixtures(): def load_fixtures():
@ -43,229 +39,164 @@ def load_fixtures():
return [fixture_data] return [fixture_data]
@pytest.fixture(autouse=True)
def module_mock(mocker):
connection_class_mock = mocker.patch('ansible.module_utils.basic.AnsibleModule')
return connection_class_mock
@pytest.fixture(autouse=True)
def connection_mock(mocker):
connection_class_mock = mocker.patch('ansible.modules.network.fortimanager.fmgr_device_group.Connection')
return connection_class_mock
@pytest.fixture(scope="function", params=load_fixtures()) @pytest.fixture(scope="function", params=load_fixtures())
def fixture_data(request): def fixture_data(request):
func_name = request.function.__name__.replace("test_", "") func_name = request.function.__name__.replace("test_", "")
return request.param.get(func_name, None) return request.param.get(func_name, None)
def test_add_device_group(fixture_data, mocker): fmg_instance = FortiManagerHandler(connection_mock, module_mock)
mocker.patch(
"pyFMG.fortimgr.FortiManager._post_request",
side_effect=fixture_data)
paramgram_used = {
'grp_desc': 'CreatedbyAnsible', def test_add_device_group(fixture_data, mocker):
'adom': 'ansible', mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request",
'grp_members': None, side_effect=fixture_data)
'state': 'present', # Fixture sets used:###########################
'grp_name': 'TestGroup',
'vdom': 'root', ##################################################
'mode': 'add'}
output = fmgr_device_group.add_device_group(fmg_instance, paramgram_used)
#
# grp_desc: CreatedbyAnsible # grp_desc: CreatedbyAnsible
# adom: ansible # adom: ansible
# grp_members: None # grp_members: None
# state: present # mode: add
# grp_name: TestGroup # grp_name: TestGroup
# vdom: root # vdom: root
# mode: add ##################################################
# ##################################################
assert output['raw_response']['status']['code'] == 0
paramgram_used = {
'grp_desc': 'CreatedbyAnsible',
'adom': 'ansible',
'grp_members': None,
'state': 'present',
'grp_name': 'testtest',
'vdom': 'root',
'mode': 'add'}
output = fmgr_device_group.add_device_group(fmg_instance, paramgram_used)
#
# grp_desc: CreatedbyAnsible # grp_desc: CreatedbyAnsible
# adom: ansible # adom: ansible
# grp_members: None # grp_members: None
# state: present # mode: add
# grp_name: testtest # grp_name: testtest
# vdom: root # vdom: root
# mode: add ##################################################
# ##################################################
assert output['raw_response']['status']['code'] == 0
paramgram_used = {
'grp_desc': None,
'adom': 'ansible',
'grp_members': 'FGT1,FGT2',
'state': 'present',
'grp_name': 'TestGroup',
'vdom': 'root',
'mode': 'add'}
output = fmgr_device_group.add_device_group(fmg_instance, paramgram_used)
#
# grp_desc: None # grp_desc: None
# adom: ansible # adom: ansible
# grp_members: FGT1,FGT2 # grp_members: FGT1
# state: present # mode: add
# grp_name: TestGroup # grp_name: TestGroup
# vdom: root # vdom: root
# mode: add ##################################################
# ##################################################
assert output['raw_response']['status']['code'] == -2
paramgram_used = {
'grp_desc': None,
'adom': 'ansible',
'grp_members': 'FGT3',
'state': 'present',
'grp_name': 'testtest',
'vdom': 'root',
'mode': 'add'}
output = fmgr_device_group.add_device_group(fmg_instance, paramgram_used)
#
# grp_desc: None # grp_desc: None
# adom: ansible # adom: ansible
# grp_members: FGT3 # grp_members: FGT3
# state: present # mode: add
# grp_name: testtest # grp_name: testtest
# vdom: root # vdom: root
# mode: add ##################################################
#
# Test using fixture 1 #
output = fmgr_device_group.add_device_group(fmg_instance, fixture_data[0]['paramgram_used'])
assert output['raw_response']['status']['code'] == -2
# Test using fixture 2 #
output = fmgr_device_group.add_device_group(fmg_instance, fixture_data[1]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0
# Test using fixture 3 #
output = fmgr_device_group.add_device_group(fmg_instance, fixture_data[2]['paramgram_used'])
assert output['raw_response']['status']['code'] == -2
# Test using fixture 4 #
output = fmgr_device_group.add_device_group(fmg_instance, fixture_data[3]['paramgram_used'])
assert output['raw_response']['status']['code'] == -2 assert output['raw_response']['status']['code'] == -2
def test_delete_device_group(fixture_data, mocker): def test_delete_device_group(fixture_data, mocker):
mocker.patch( mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request",
"pyFMG.fortimgr.FortiManager._post_request", side_effect=fixture_data)
side_effect=fixture_data) # Fixture sets used:###########################
paramgram_used = { ##################################################
'grp_desc': 'CreatedbyAnsible',
'adom': 'ansible',
'grp_members': None,
'state': 'absent',
'grp_name': 'TestGroup',
'vdom': 'root',
'mode': 'delete'}
output = fmgr_device_group.delete_device_group(
fmg_instance, paramgram_used)
#
# grp_desc: CreatedbyAnsible # grp_desc: CreatedbyAnsible
# adom: ansible # adom: ansible
# grp_members: None # grp_members: None
# state: absent # mode: delete
# grp_name: TestGroup # grp_name: TestGroup
# vdom: root # vdom: root
# mode: delete ##################################################
# ##################################################
assert output['raw_response']['status']['code'] == 0
paramgram_used = {
'grp_desc': 'CreatedbyAnsible',
'adom': 'ansible',
'grp_members': None,
'state': 'absent',
'grp_name': 'testtest',
'vdom': 'root',
'mode': 'delete'}
output = fmgr_device_group.delete_device_group(
fmg_instance, paramgram_used)
#
# grp_desc: CreatedbyAnsible # grp_desc: CreatedbyAnsible
# adom: ansible # adom: ansible
# grp_members: None # grp_members: None
# state: absent # mode: delete
# grp_name: testtest # grp_name: testtest
# vdom: root # vdom: root
# mode: delete ##################################################
#
# Test using fixture 1 #
output = fmgr_device_group.delete_device_group(fmg_instance, fixture_data[0]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0
# Test using fixture 2 #
output = fmgr_device_group.delete_device_group(fmg_instance, fixture_data[1]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0 assert output['raw_response']['status']['code'] == 0
def test_add_group_member(fixture_data, mocker): def test_add_group_member(fixture_data, mocker):
mocker.patch( mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request",
"pyFMG.fortimgr.FortiManager._post_request", side_effect=fixture_data)
side_effect=fixture_data) # Fixture sets used:###########################
paramgram_used = { ##################################################
'grp_desc': None,
'adom': 'ansible',
'grp_members': 'FGT1,FGT2',
'state': 'present',
'grp_name': 'TestGroup',
'vdom': 'root',
'mode': 'add'}
output = fmgr_device_group.add_group_member(fmg_instance, paramgram_used)
#
# grp_desc: None # grp_desc: None
# adom: ansible # adom: ansible
# grp_members: FGT1,FGT2 # grp_members: FGT1
# state: present # mode: add
# grp_name: TestGroup # grp_name: TestGroup
# vdom: root # vdom: root
# mode: add ##################################################
# ##################################################
assert output['raw_response']['status']['code'] == 0
paramgram_used = {
'grp_desc': None,
'adom': 'ansible',
'grp_members': 'FGT3',
'state': 'present',
'grp_name': 'testtest',
'vdom': 'root',
'mode': 'add'}
output = fmgr_device_group.add_group_member(fmg_instance, paramgram_used)
#
# grp_desc: None # grp_desc: None
# adom: ansible # adom: ansible
# grp_members: FGT3 # grp_members: FGT3
# state: present # mode: add
# grp_name: testtest # grp_name: testtest
# vdom: root # vdom: root
# mode: add ##################################################
#
# Test using fixture 1 #
output = fmgr_device_group.add_group_member(fmg_instance, fixture_data[0]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0
# Test using fixture 2 #
output = fmgr_device_group.add_group_member(fmg_instance, fixture_data[1]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0 assert output['raw_response']['status']['code'] == 0
def test_delete_group_member(fixture_data, mocker): def test_delete_group_member(fixture_data, mocker):
mocker.patch( mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request",
"pyFMG.fortimgr.FortiManager._post_request", side_effect=fixture_data)
side_effect=fixture_data) # Fixture sets used:###########################
paramgram_used = { ##################################################
'grp_desc': None,
'adom': 'ansible',
'grp_members': 'FGT3',
'state': 'absent',
'grp_name': 'testtest',
'vdom': 'root',
'mode': 'delete'}
output = fmgr_device_group.delete_group_member(
fmg_instance, paramgram_used)
#
# grp_desc: None # grp_desc: None
# adom: ansible # adom: ansible
# grp_members: FGT3 # grp_members: FGT3
# state: absent # mode: delete
# grp_name: testtest # grp_name: testtest
# vdom: root # vdom: root
# mode: delete ##################################################
# ##################################################
assert output['raw_response']['status']['code'] == 0
paramgram_used = {
'grp_desc': None,
'adom': 'ansible',
'grp_members': 'FGT1,FGT2',
'state': 'absent',
'grp_name': 'TestGroup',
'vdom': 'root',
'mode': 'delete'}
output = fmgr_device_group.delete_group_member(
fmg_instance, paramgram_used)
#
# grp_desc: None # grp_desc: None
# adom: ansible # adom: ansible
# grp_members: FGT1,FGT2 # grp_members: FGT1
# state: absent # mode: delete
# grp_name: TestGroup # grp_name: TestGroup
# vdom: root # vdom: root
# mode: delete ##################################################
#
# Test using fixture 1 #
output = fmgr_device_group.delete_group_member(fmg_instance, fixture_data[0]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0
# Test using fixture 2 #
output = fmgr_device_group.delete_group_member(fmg_instance, fixture_data[1]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0