Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

network and install policy modules for example #55446

Closed
wants to merge 22 commits into from
Closed
Changes from 18 commits
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

@@ -26,34 +26,223 @@
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

from __future__ import (absolute_import, division, print_function)

checkpoint_argument_spec = dict(auto_publish_session=dict(type='bool', default=True),

This comment has been minimized.

Copy link
@justjais

justjais Jun 10, 2019

Contributor

plz do not, change this else if the tests written by Ricky would be using respective params shippable-tests will fail and we'll not be able to proceed further, please put a comment for these param as used by checkpoint_* modules which shall be deprecated in future.

This comment has been minimized.

Copy link
@chkp-orso

chkp-orso Jun 10, 2019

Author Contributor

ok thanks

policy_package=dict(type='str', default='standard'),
auto_install_policy=dict(type='bool', default=True),
targets=dict(type='list')
)
import time

from ansible.module_utils.connection import Connection

def publish(connection, uid=None):
payload = None

if uid:
payload = {'uid': uid}
checkpoint_argument_spec_for_objects = dict(
name=dict(type='str'),
uid=dict(type='str'),
tags=dict(type='list'),
color=dict(type='str', choices=['aquamarine', 'black', 'blue', 'crete blue', 'burlywood', 'cyan', 'dark green',
'khaki', 'orchid', 'dark orange', 'dark sea green', 'pink', 'turquoise',
'dark blue', 'firebrick', 'brown', 'forest green', 'gold', 'dark gold', 'gray',
'dark gray', 'light green', 'lemon chiffon', 'coral', 'sea green', 'sky blue',
'magenta', 'purple', 'slate blue', 'violet red', 'navy blue', 'olive', 'orange',
'red', 'sienna', 'yellow']),
comments=dict(type='str'),
details_level=dict(type='str', choices=['uid', 'standard', 'full']),
groups=dict(type='list'),
ignore_warnings=dict(type='bool'),
ignore_errors=dict(type='bool'),
new_name=dict(type='str'),
auto_publish_session=dict(type='bool'),
wait_for_task=dict(type='bool', default=True),
state=dict(type='str', required=True, choices=['present', 'absent']),
version=dict(type='str')
)

connection.send_request('/web_api/publish', payload)
checkpoint_argument_spec_for_facts = dict(
name=dict(type='str'),
uid=dict(type='str'),
details_level=dict(type='str', choices=['uid', 'standard', 'full']),
limit=dict(type='int'),
offset=dict(type='int'),
order=dict(type='list'),
show_membership=dict(type='bool'),
version=dict(type='str')
)

checkpoint_argument_spec_for_commands = dict(
wait_for_task=dict(type='bool', default=True),
version=dict(type='str')
)

def discard(connection, uid=None):
payload = None

if uid:
payload = {'uid': uid}
# send the request to checkpoint
def send_request(connection, version, url, payload=None):
code, response = connection.send_request('/web_api/' + version + url, payload)

connection.send_request('/web_api/discard', payload)
return code, response


def install_policy(connection, policy_package, targets):
payload = {'policy-package': policy_package,
'targets': targets}
# get the payload from the user parameters
def is_checkpoint_param(parameter):
if parameter == 'auto_publish_session' or\
parameter == 'state' or\
parameter == 'wait_for_task' or\
parameter == 'version':
return False
return True

connection.send_request('/web_api/install-policy', payload)

# build the payload from the parameters which has value (not None), and they are parameter of checkpoint API as well
def get_payload_from_parameters(module):
payload = {}
for parameter in module.params:
if module.params[parameter] and is_checkpoint_param(parameter):
payload[parameter.replace("_", "-")] = module.params[parameter]
return payload


# wait for task
def wait_for_task(module, version, connection, task_id):
task_id_payload = {'task-id': task_id}
task_complete = False
current_iteration = 0
max_num_iterations = 300

# As long as there is a task in progress
while not task_complete and current_iteration < max_num_iterations:
current_iteration += 1
# Check the status of the task
code, response = send_request(connection, version, 'show-task', task_id_payload)

attempts_counter = 0
while code != 200:
if attempts_counter < 5:
attempts_counter += 1
time.sleep(2)
code, response = send_request(connection, version, 'show-task', task_id_payload)
else:
response['message'] = "ERROR: Failed to handle asynchronous tasks as synchronous, tasks result is" \
" undefined.\n" + response['message']
module.fail_json(msg=response)

# Count the number of tasks that are not in-progress
completed_tasks = 0
for task in response['tasks']:
if task['status'] == 'failed':
module.fail_json(msg='Task {0} with task id {1} failed. Look at the logs for more details'
.format(task['task-name'], task['task-id']))
if task['status'] == 'in progress':
break
completed_tasks += 1

# Are we done? check if all tasks are completed
if completed_tasks == len(response["tasks"]):
task_complete = True
else:
time.sleep(2) # Wait for two seconds
if not task_complete:
module.fail_json(msg="ERROR: Timeout.\nTask-id: {0}.".format(task_id_payload['task-id']))


# handle publish command, and wait for it to end if the user asked so
def handle_publish(module, connection, version):
if module.params['auto_publish_session']:
publish_code, publish_response = send_request(connection, version, 'publish')
if publish_code != 200:
module.fail_json(msg=publish_response)
if module.params['wait_for_task']:
wait_for_task(module, version, connection, publish_response['task-id'])


# handle a command
def api_command(module, command):
payload = get_payload_from_parameters(module)
connection = Connection(module._socket_path)
# if user insert a specific version, we add it to the url
version = ('v' + module.params['version'] + '/') if module.params['version'] else ''

code, response = send_request(connection, version, command, payload)
result = {'changed': True}

if code == 200:
if module.params['wait_for_task']:
if 'task-id' in response:
wait_for_task(module, version, connection, response['task-id'])
elif 'tasks' in response:
for task_id in response['tasks']:
wait_for_task(module, version, connection, task_id)

result['checkpoint_' + command.replace("-", "_")] = response
else:
module.fail_json(msg='Checkpoint device returned error {0} with message {1}'.format(code, response))

module.exit_json(**result)


# handle api call facts
def api_call_facts(module, api_call_object, api_call_object_plural_version):

This comment has been minimized.

Copy link
@justjais

justjais Jun 10, 2019

Contributor

@chkp-orso Is this required, if we'll be handling facts module under lookup plugins

This comment has been minimized.

Copy link
@chkp-orso

chkp-orso Jun 10, 2019

Author Contributor

amm u r right, I will delete it

This comment has been minimized.

Copy link
@justjais

justjais Jun 10, 2019

Contributor

ok

payload = get_payload_from_parameters(module)
connection = Connection(module._socket_path)
# if user insert a specific version, we add it to the url
version = ('v' + module.params['version'] + '/') if module.params['version'] else ''

# if there is neither name nor uid, the API command will be in plural version (e.g. show-hosts instead of show-host)
if payload.get("name") is None and payload.get("uid") is None:
api_call_object = api_call_object_plural_version

code, response = send_request(connection, version, 'show-' + api_call_object, payload)
if code == 200:
module.exit_json(ansible_facts={api_call_object: response})
else:
module.fail_json(msg='Checkpoint device returned error {0} with message {1}'.format(code, response))


# handle api call
def api_call(module, api_call_object):
payload = get_payload_from_parameters(module)
connection = Connection(module._socket_path)
# if user insert a specific version, we add it to the url
version = ('v' + module.params['version'] + '/') if module.params['version'] else ''

payload_for_equals = {'type': api_call_object, 'params': payload}
equals_code, equals_response = send_request(connection, version, 'equals', payload_for_equals)
# if code is 400 (bad request) or 500 (internal error) - fail
if equals_code == 400 or equals_code == 500:
module.fail_json(msg=equals_response)
result = {'changed': False}

if module.params['state'] == 'present':
if equals_code == 200:
if not equals_response['equals']:
code, response = send_request(connection, version, 'set-' + api_call_object, payload)
if code != 200:
module.fail_json(msg=response)

handle_publish(module, connection, version)

result['changed'] = True
result[api_call_object] = response
else:
# objects are equals and there is no need for set request
pass
elif equals_code == 404:
code, response = send_request(connection, version, 'add-' + api_call_object, payload)
if code != 200:
module.fail_json(msg=response)

handle_publish(module, connection, version)

result['changed'] = True
result[api_call_object] = response
else:
if equals_code == 200:
code, response = send_request(connection, version, 'delete-' + api_call_object, payload)
if code != 200:
module.fail_json(msg=response)

handle_publish(module, connection, version)

result['changed'] = True
elif equals_code == 404:
# no need to delete because object dose not exist
pass

result['checkpoint_session_uid'] = connection.get_session_uid()
module.exit_json(**result)
@@ -52,10 +52,10 @@
"""

RETURN = """
ansible_facts:
description: The checkpoint access layer facts.
api_result:

This comment has been minimized.

Copy link
@justjais

justjais May 13, 2019

Contributor

@chkp-orso why have u modified return param from ansible_facts to api_result

This comment has been minimized.

Copy link
@chkp-orso

chkp-orso May 13, 2019

Author Contributor

@justjais because I wanted it to be consistent, means all the files return api_result.. (all the modules and all the commands like install policy return api_result).
Isn't it better?

This comment has been minimized.

Copy link
@justjais

justjais May 13, 2019

Contributor

@chkp-orso to be consistent with other Ansible resource module, it's better to have as is. Also, it's better to have each module returns the module facts instead of common return.

This comment has been minimized.

Copy link
@chkp-orso

chkp-orso May 15, 2019

Author Contributor

@justjais So to write "ansible_facts" or "checkpoint_access_layer_facts" ?

This comment has been minimized.

Copy link
@justjais

justjais May 15, 2019

Contributor

@chkp-orso for already existing module, u need not to change the return values, respective comment was for future modules

This comment has been minimized.

Copy link
@chkp-orso

chkp-orso May 15, 2019

Author Contributor

@justjais amm but I would prefer all the modules to be consistent..
because I create all the modules automatically with the tool..

This comment has been minimized.

Copy link
@chkp-orso

chkp-orso May 15, 2019

Author Contributor

So I would prefer to return "ansible_facts" or "checkpoint_access_layer_facts" to all files

This comment has been minimized.

Copy link
@justjais

justjais May 16, 2019

Contributor

@chkp-orso It's better to return the facts with the module name, but if not u can return with ansible_facts for e.g. for module checkpoint_host the return value is checkpoint_hosts but for module checkpoint_access_layer_facts the return value is ansible_facts

This comment has been minimized.

Copy link
@chkp-orso

chkp-orso May 16, 2019

Author Contributor

@justjais OK, so anyway because we prefer to be consistent, we will return "ansible_facts" to all the modules

description: The checkpoint object facts.
returned: always.
type: list
type: dict
"""


@@ -71,27 +71,6 @@
- State of the access rule (present or absent). Defaults to present.
type: str
default: present
auto_publish_session:

This comment has been minimized.

Copy link
@justjais

justjais Jun 10, 2019

Contributor

since this module will be deprecated, plz remove these modules as is meaning do not change any thing in modules written by Ricky

description:
- Publish the current session if changes have been performed
after task completes.
type: bool
default: 'yes'
auto_install_policy:
description:
- Install the package policy if changes have been performed
after the task completes.
type: bool
default: 'yes'
policy_package:
description:
- Package policy name to be installed.
type: str
default: 'standard'
targets:
description:
- Targets to install the package policy on.
type: list
"""

EXAMPLES = """
@@ -103,24 +82,22 @@
source: attacker
destination: Any
action: Drop
- name: Delete access rule
checkpoint_access_rule:
layer: Network
name: "Drop attacker"
"""

RETURN = """
checkpoint_access_rules:
description: The checkpoint access rule object created or updated.
returned: always, except when deleting the access rule.
type: list
api_result:

This comment has been minimized.

Copy link
@justjais

justjais May 13, 2019

Contributor

Return value is the value which is being returned as result to user and in this case result['checkpoint_access_rules'] is being returned as output to user, so u need not not modify the return if the param name itself is not changed.

description: The checkpoint object created or updated.
returned: always, except when deleting the object.
type: dict
"""


from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.checkpoint.checkpoint import checkpoint_argument_spec, publish, install_policy
import json


@@ -216,7 +193,6 @@ def main():
enabled=dict(type='bool', default=True),
state=dict(type='str', default='present')
)
argument_spec.update(checkpoint_argument_spec)

required_if = [('state', 'present', ('layer', 'position'))]
module = AnsibleModule(argument_spec=argument_spec, required_if=required_if)
@@ -230,11 +206,6 @@ def main():
code, response = update_access_rule(module, connection)
if code != 200:
module.fail_json(msg=response)
if module.params['auto_publish_session']:
publish(connection)

if module.params['auto_install_policy']:
install_policy(connection, module.params['policy_package'], module.params['targets'])

result['changed'] = True
result['checkpoint_access_rules'] = response
@@ -244,11 +215,6 @@ def main():
code, response = create_access_rule(module, connection)
if code != 200:
module.fail_json(msg=response)
if module.params['auto_publish_session']:
publish(connection)

if module.params['auto_install_policy']:
install_policy(connection, module.params['policy_package'], module.params['targets'])

result['changed'] = True
result['checkpoint_access_rules'] = response
@@ -257,11 +223,6 @@ def main():
code, response = delete_access_rule(module, connection)
if code != 200:
module.fail_json(msg=response)
if module.params['auto_publish_session']:
publish(connection)

if module.params['auto_install_policy']:
install_policy(connection, module.params['policy_package'], module.params['targets'])

result['changed'] = True
result['checkpoint_access_rules'] = response
@@ -59,10 +59,10 @@
"""

RETURN = """
ansible_facts:
description: The checkpoint access rule object facts.
api_result:

This comment has been minimized.

Copy link
@justjais

justjais May 13, 2019

Contributor

same as previous module return comment.

description: The checkpoint object facts.
returned: always.
type: list
type: dict
"""


ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.