| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
from __future__ import absolute_import, division, print_function |
| 29 |
|
| 30 |
__metaclass__ = type |
| 31 |
from ansible.module_utils.basic import _load_params |
| 32 |
import datetime |
| 33 |
import re |
| 34 |
import os |
| 35 |
|
| 36 |
try: |
| 37 |
import yaml |
| 38 |
except ImportError as imp_exc: |
| 39 |
YAML_IMPORT_ERROR = imp_exc |
| 40 |
else: |
| 41 |
YAML_IMPORT_ERROR = None |
| 42 |
|
| 43 |
|
| 44 |
RENAME_ARG = {"message": "fmgr_message", |
| 45 |
"syslog-facility": "fmgr_syslog_facility", |
| 46 |
"80211d": "d80211d", |
| 47 |
"80211k": "d80211k", |
| 48 |
"80211v": "d80211v", |
| 49 |
"80211mc": "d80211mc"} |
| 50 |
VERSION_CHECK = os.getenv("ANSIBLE_FORTIMANAGER_VERSION_CHECK", "true").lower() in ["true", "1", "yes", "y", "t"] |
| 51 |
|
| 52 |
|
| 53 |
def check_galaxy_version(schema): |
| 54 |
params = _load_params() |
| 55 |
if not params: |
| 56 |
return |
| 57 |
params_keys = list(params.keys()) |
| 58 |
if "method" in params_keys and "method" not in schema: |
| 59 |
error_message = "Legacy playbook detected, please revise the playbook or install latest legacy" |
| 60 |
error_message += " fortimanager galaxy collection: #ansible-galaxy collection install -f fortinet.fortimanager:1.0.5" |
| 61 |
raise Exception(error_message) |
| 62 |
|
| 63 |
|
| 64 |
def get_bypass(params): |
| 65 |
bypass = params.get("bypass_validation", False) |
| 66 |
if isinstance(bypass, bool): |
| 67 |
return bypass |
| 68 |
elif isinstance(bypass, str): |
| 69 |
return bypass.lower() in ["true", "y", "yes", "t", "1", "on"] |
| 70 |
elif isinstance(bypass, int): |
| 71 |
return bypass != 0 |
| 72 |
return True |
| 73 |
|
| 74 |
|
| 75 |
def check_parameter_bypass(schema, module_level2_name): |
| 76 |
schema = modify_argument_spec(schema) |
| 77 |
params = _load_params() |
| 78 |
if not params: |
| 79 |
return schema |
| 80 |
is_bypass = get_bypass(params) |
| 81 |
if is_bypass: |
| 82 |
top_level_schema = dict() |
| 83 |
for key in schema: |
| 84 |
if key != module_level2_name: |
| 85 |
top_level_schema[key] = schema[key] |
| 86 |
elif ( |
| 87 |
not params[module_level2_name] |
| 88 |
or isinstance(params[module_level2_name], dict) |
| 89 |
): |
| 90 |
top_level_schema[module_level2_name] = {"type": "dict"} |
| 91 |
elif isinstance(params[module_level2_name], list): |
| 92 |
top_level_schema[module_level2_name] = {"type": "list"} |
| 93 |
return top_level_schema |
| 94 |
return schema |
| 95 |
|
| 96 |
|
| 97 |
def modify_argument_spec(schema): |
| 98 |
if not isinstance(schema, dict): |
| 99 |
return schema |
| 100 |
new_schema = {} |
| 101 |
for param_name in schema: |
| 102 |
if param_name != "v_range" and param_name != "api_name": |
| 103 |
new_content = modify_argument_spec(schema[param_name]) |
| 104 |
aliase_name = get_ansible_format_name(param_name) |
| 105 |
if param_name in RENAME_ARG: |
| 106 |
new_content["removed_in_version"] = "3.0.0" |
| 107 |
new_content["removed_from_collection"] = "fortinet.fortimanager" |
| 108 |
new_content["aliases"] = [RENAME_ARG[param_name]] |
| 109 |
elif aliase_name != param_name: |
| 110 |
new_content["removed_in_version"] = "3.0.0" |
| 111 |
new_content["removed_from_collection"] = "fortinet.fortimanager" |
| 112 |
if aliase_name not in schema and "api_name" not in schema[param_name]: |
| 113 |
new_content["aliases"] = [aliase_name] |
| 114 |
new_schema[param_name] = new_content |
| 115 |
return new_schema |
| 116 |
|
| 117 |
|
| 118 |
def get_ansible_format_name(api_format_name, replace_param=False): |
| 119 |
ansible_format_name = api_format_name |
| 120 |
for special_char in ["-", " ", ".", "(", "+"]: |
| 121 |
ansible_format_name = ansible_format_name.replace(special_char, "_") |
| 122 |
for special_char in [")"]: |
| 123 |
ansible_format_name = ansible_format_name.replace(special_char, "") |
| 124 |
if replace_param and ansible_format_name in RENAME_ARG: |
| 125 |
ansible_format_name = RENAME_ARG[ansible_format_name] |
| 126 |
return ansible_format_name |
| 127 |
|
| 128 |
|
| 129 |
def get_ansible_format_params(params): |
| 130 |
|
| 131 |
if isinstance(params, dict): |
| 132 |
ansible_params = {} |
| 133 |
for param_name in params: |
| 134 |
ansible_format_name = get_ansible_format_name(param_name, replace_param=True) |
| 135 |
ansible_params[ansible_format_name] = get_ansible_format_params(params[param_name]) |
| 136 |
return ansible_params |
| 137 |
if isinstance(params, list): |
| 138 |
ansible_params = [] |
| 139 |
for param_item in params: |
| 140 |
ansible_params.append(get_ansible_format_params(param_item)) |
| 141 |
return ansible_params |
| 142 |
return params |
| 143 |
|
| 144 |
|
| 145 |
def remove_aliases(user_params, metadata, bypass_valid=False): |
| 146 |
if not user_params: |
| 147 |
return user_params |
| 148 |
if isinstance(user_params, list): |
| 149 |
new_params = [] |
| 150 |
for item in user_params: |
| 151 |
new_params.append(remove_aliases(item, metadata, bypass_valid)) |
| 152 |
return new_params |
| 153 |
elif isinstance(user_params, dict): |
| 154 |
replace_key = {"fmgr_message": "message"} |
| 155 |
new_params = {} |
| 156 |
considered_keys = set() |
| 157 |
for api_format_name, param_data in metadata.items(): |
| 158 |
ansible_format_name = get_ansible_format_name(api_format_name) |
| 159 |
api_format_name = replace_key.get(api_format_name, api_format_name) |
| 160 |
considered_keys.add(api_format_name) |
| 161 |
considered_keys.add(ansible_format_name) |
| 162 |
user_data = user_params.get(api_format_name, None) |
| 163 |
if user_data is None: |
| 164 |
user_data = user_params.get(ansible_format_name, None) |
| 165 |
if user_data is None: |
| 166 |
continue |
| 167 |
if "options" in param_data: |
| 168 |
new_params[api_format_name] = remove_aliases(user_data, param_data["options"], bypass_valid) |
| 169 |
else: |
| 170 |
new_params[api_format_name] = user_data |
| 171 |
if bypass_valid: |
| 172 |
for api_format_name, param_data in user_params.items(): |
| 173 |
if api_format_name not in considered_keys: |
| 174 |
new_params[api_format_name] = param_data |
| 175 |
return new_params |
| 176 |
|
| 177 |
return new_params |
| 178 |
|
| 179 |
|
| 180 |
def is_basic_data_format(data): |
| 181 |
if isinstance(data, str): |
| 182 |
return True |
| 183 |
if isinstance(data, int): |
| 184 |
return True |
| 185 |
if isinstance(data, float): |
| 186 |
return True |
| 187 |
if isinstance(data, bool): |
| 188 |
return True |
| 189 |
return False |
| 190 |
|
| 191 |
|
| 192 |
class NAPIManager(object): |
| 193 |
def __init__(self, task_type, metadata, urls_list, module_primary_key, top_level_schema_name, |
| 194 |
module, conn): |
| 195 |
self.urls_list = urls_list |
| 196 |
self.module_primary_key = module_primary_key |
| 197 |
self.module = module |
| 198 |
self.conn = conn |
| 199 |
self.module_name = self.module._name |
| 200 |
self.module_level2_name = self.module_name.split(".")[-1][5:] |
| 201 |
self.top_level_schema_name = top_level_schema_name |
| 202 |
self._set_connection_options() |
| 203 |
self._process_workspace_lock() |
| 204 |
self.version_check_warnings = list() |
| 205 |
self._nr_exported_playbooks = 0 |
| 206 |
self._nr_valid_selectors = 0 |
| 207 |
self.metadata = metadata |
| 208 |
if metadata is None: |
| 209 |
self.metadata = {} |
| 210 |
self.task_type = task_type |
| 211 |
self.diff_data = {"before": {}, "after": {}} |
| 212 |
self.allow_diff = False |
| 213 |
self.extra_params = self._init_extra_params() |
| 214 |
self.system_status = self.get_system_status() |
| 215 |
if YAML_IMPORT_ERROR: |
| 216 |
raise Exception("YAML must be installed to use this plugin") |
| 217 |
|
| 218 |
def _init_extra_params(self): |
| 219 |
extra_params = {} |
| 220 |
params = self.module.params |
| 221 |
if params.get("revision_note", ""): |
| 222 |
extra_params["revision_note"] = params["revision_note"] |
| 223 |
return extra_params |
| 224 |
|
| 225 |
def _set_connection_options(self): |
| 226 |
for key in ["access_token", "enable_log", "forticloud_access_token"]: |
| 227 |
if key in self.module.params: |
| 228 |
self.conn.set_customer_option(key, self.module.params[key]) |
| 229 |
|
| 230 |
def _process_workspace_lock(self): |
| 231 |
self.conn.process_workspace_locking(self.module.params) |
| 232 |
|
| 233 |
def process_generic(self, method, param): |
| 234 |
response = self.conn.send_request(method, param) |
| 235 |
self.do_exit(response) |
| 236 |
|
| 237 |
def process_exec(self): |
| 238 |
argument_specs = self.metadata |
| 239 |
params = self.module.params |
| 240 |
module_name = self.module_level2_name |
| 241 |
version_check = params.get("version_check", VERSION_CHECK) |
| 242 |
bypass_valid = params.get("bypass_validation", False) |
| 243 |
if version_check and not bypass_valid: |
| 244 |
track = [module_name] |
| 245 |
self.check_versioning_mismatch(track, argument_specs.get(module_name, None), params.get(module_name, None)) |
| 246 |
target_url = self.get_target_url() |
| 247 |
api_params = {"url": target_url} |
| 248 |
if module_name in params: |
| 249 |
params = remove_aliases(params, argument_specs, bypass_valid) |
| 250 |
api_params[self.top_level_schema_name] = params[module_name] |
| 251 |
if self.module.check_mode: |
| 252 |
self.do_final_exit(changed=True) |
| 253 |
response = self.conn.send_request("exec", [api_params]) |
| 254 |
self.do_exit(response) |
| 255 |
|
| 256 |
def process_task(self): |
| 257 |
metadata = self.metadata |
| 258 |
task_type = self.task_type |
| 259 |
params = self.module.params |
| 260 |
selector = params[task_type]["selector"] |
| 261 |
param_url_id = "params" if task_type == "facts" else "self" |
| 262 |
specified_url_param = params[task_type][param_url_id] |
| 263 |
specified_url_param = specified_url_param if specified_url_param else {} |
| 264 |
param_target = params[task_type].get("target", {}) |
| 265 |
param_target = param_target if param_target else {} |
| 266 |
mkey = metadata[selector].get("mkey", None) |
| 267 |
if mkey and not mkey.startswith("complex:") and mkey not in param_target: |
| 268 |
modified_mkey = get_ansible_format_name(mkey) |
| 269 |
if modified_mkey in param_target: |
| 270 |
param_target[mkey] = param_target[modified_mkey] |
| 271 |
del param_target[modified_mkey] |
| 272 |
else: |
| 273 |
self.module.fail_json(msg="Must give the primary key/value in target: %s!" % (mkey)) |
| 274 |
vrange = metadata[selector].get("v_range", None) |
| 275 |
matched, checking_message = self.is_version_matched(vrange) |
| 276 |
if not matched: |
| 277 |
self.version_check_warnings.append("selector:%s %s" % (selector, checking_message)) |
| 278 |
|
| 279 |
param_map = {} |
| 280 |
specified_params = set() |
| 281 |
for param_name in metadata[selector]["params"]: |
| 282 |
modified_name = get_ansible_format_name(param_name) |
| 283 |
if modified_name in specified_url_param: |
| 284 |
param_map[param_name] = modified_name |
| 285 |
specified_params.add(param_name) |
| 286 |
elif param_name in specified_url_param: |
| 287 |
param_map[param_name] = param_name |
| 288 |
specified_params.add(param_name) |
| 289 |
url_with_specified_param = [] |
| 290 |
unique_url_params = [] |
| 291 |
for possible_url in metadata[selector]["urls"]: |
| 292 |
url_params = set(self.get_params_in_url(possible_url)) |
| 293 |
if "adom" in metadata[selector]["params"]: |
| 294 |
url_params.add("adom") |
| 295 |
if specified_params == url_params: |
| 296 |
url_with_specified_param.append(possible_url) |
| 297 |
if url_params not in unique_url_params: |
| 298 |
unique_url_params.append(url_params) |
| 299 |
if len(url_with_specified_param) == 0: |
| 300 |
error_message = "Expect required params: " |
| 301 |
for i, url_params in enumerate(unique_url_params): |
| 302 |
if i: |
| 303 |
error_message += ", or " |
| 304 |
error_message += "%s" % ([get_ansible_format_name(key) for key in url_params]) |
| 305 |
self.module.fail_json(msg=error_message) |
| 306 |
adom_value = specified_url_param.get("adom", None) |
| 307 |
target_url = self.get_target_url_template(adom_value, url_with_specified_param) |
| 308 |
for param in param_map: |
| 309 |
token_hint = "{%s}" % (param) |
| 310 |
user_param_name = param_map[param] |
| 311 |
token = "%s" % (specified_url_param[user_param_name]) if specified_url_param[user_param_name] else "" |
| 312 |
target_url = target_url.replace(token_hint, token) |
| 313 |
|
| 314 |
request_type = {"clone": "clone", "rename": "update", |
| 315 |
"move": "move", "facts": "get"} |
| 316 |
api_params = {"url": target_url} |
| 317 |
if task_type in ["clone", "rename"]: |
| 318 |
api_params["data"] = param_target |
| 319 |
elif task_type == "move": |
| 320 |
api_params["option"] = params[task_type]["action"] |
| 321 |
api_params["target"] = param_target |
| 322 |
elif task_type == "facts": |
| 323 |
fact_params = params["facts"] |
| 324 |
for key in ["filter", "sortings", "fields", "option"]: |
| 325 |
if fact_params.get(key, None): |
| 326 |
api_params[key] = fact_params[key] |
| 327 |
if fact_params.get("extra_params", None): |
| 328 |
for key in fact_params["extra_params"]: |
| 329 |
api_params[key] = fact_params["extra_params"][key] |
| 330 |
if self.module.check_mode: |
| 331 |
if task_type in ["clone", "rename", "move"]: |
| 332 |
self.do_final_exit(changed=True) |
| 333 |
response = self.conn.send_request(request_type[task_type], [api_params]) |
| 334 |
self.do_exit(response, changed=(task_type != "facts")) |
| 335 |
|
| 336 |
def process_object_member(self): |
| 337 |
argument_specs = self.metadata |
| 338 |
module_name = self.module_level2_name |
| 339 |
params = self.module.params |
| 340 |
version_check = params.get("version_check", VERSION_CHECK) |
| 341 |
bypass_valid = self.module.params.get("bypass_validation", False) |
| 342 |
if version_check and not bypass_valid: |
| 343 |
track = [module_name] |
| 344 |
self.check_versioning_mismatch(track, argument_specs.get(module_name, None), params.get(module_name, None)) |
| 345 |
member_url = self.get_target_url() |
| 346 |
parent_url, separator, task_type = member_url.rpartition("/") |
| 347 |
response = (-1, {}) |
| 348 |
object_present = remove_aliases(self.module.params, self.metadata, bypass_valid) |
| 349 |
object_present = object_present.get(self.module_level2_name, {}) |
| 350 |
if self.module.params["state"] == "present": |
| 351 |
params = [{"url": parent_url}] |
| 352 |
rc, object_remote = self.conn.send_request("get", params) |
| 353 |
if rc == 0: |
| 354 |
object_remote = object_remote.get("data", {}) |
| 355 |
object_remote = object_remote.get(task_type, {}) |
| 356 |
require_update = True |
| 357 |
if not bypass_valid: |
| 358 |
if isinstance(object_remote, list): |
| 359 |
if len(object_remote) > 1: |
| 360 |
require_update = True |
| 361 |
else: |
| 362 |
object_remote = object_remote[0] |
| 363 |
try: |
| 364 |
require_update = self.is_object_difference(object_remote, object_present) |
| 365 |
except Exception as e: |
| 366 |
pass |
| 367 |
if self.is_force_update() or require_update: |
| 368 |
response = self.update_object("") |
| 369 |
else: |
| 370 |
return_msg = "Your FortiManager is already up to date and does not need to be updated. " |
| 371 |
return_msg += "To force update, please add argument proposed_method:update" |
| 372 |
self.do_final_exit(changed=False, message=return_msg) |
| 373 |
else: |
| 374 |
resource_name = parent_url.split("/")[-1] |
| 375 |
parent_module, separator, task_name = module_name.rpartition("_") |
| 376 |
parent_module = "fmgr_" + parent_module |
| 377 |
rename_parent_module = {"fmgr_pm_devprof": "fmgr_pm_devprof_pkg", |
| 378 |
"fmgr_pm_wanprof": "fmgr_pm_wanprof_pkg"} |
| 379 |
if parent_module in rename_parent_module: |
| 380 |
parent_module = rename_parent_module[parent_module] |
| 381 |
self.module.fail_json(msg="The resource %s does not exist. Please try to use the module %s first." % |
| 382 |
(resource_name, parent_module)) |
| 383 |
elif self.module.params["state"] == "absent": |
| 384 |
params = [{"url": member_url, self.top_level_schema_name: object_present}] |
| 385 |
if self.module.check_mode: |
| 386 |
self.do_final_exit(changed=True) |
| 387 |
response = self.conn.send_request("delete", params) |
| 388 |
self.do_exit(response) |
| 389 |
|
| 390 |
def process_crud(self): |
| 391 |
self.allow_diff = True |
| 392 |
argument_specs = self.metadata |
| 393 |
params = self.module.params |
| 394 |
module_name = self.module_level2_name |
| 395 |
version_check = params.get("version_check", VERSION_CHECK) |
| 396 |
bypass_valid = params.get("bypass_validation", False) |
| 397 |
if version_check and not bypass_valid: |
| 398 |
track = [module_name] |
| 399 |
self.check_versioning_mismatch(track, argument_specs.get(module_name, None), params.get(module_name, None)) |
| 400 |
response = (-1, {}) |
| 401 |
state = params["state"] |
| 402 |
if self.module_primary_key and isinstance(params.get(module_name, None), dict): |
| 403 |
mvalue = self.get_mvalue() |
| 404 |
if state == "present": |
| 405 |
rc, remote_data = self.read_object(mvalue) |
| 406 |
self.diff_save_data_from_response("before", remote_data) |
| 407 |
if rc == 0: |
| 408 |
if self.is_force_update() or self.is_update_required(remote_data): |
| 409 |
response = self.update_object(mvalue) |
| 410 |
else: |
| 411 |
return_msg = "Your FortiManager is already up to date and does not need to be updated. " |
| 412 |
return_msg += "To force update, please add argument proposed_method:update" |
| 413 |
self.diff_save_data_from_response("after", remote_data) |
| 414 |
self.do_final_exit(changed=False, message=return_msg) |
| 415 |
else: |
| 416 |
response = self.create_object() |
| 417 |
if self.allow_diff and (self.module._diff or self.module.check_mode): |
| 418 |
rc, new_response = self.read_object(mvalue) |
| 419 |
self.diff_save_data_from_response("after", new_response) |
| 420 |
elif state == "absent": |
| 421 |
|
| 422 |
self.diff_get_and_save_data("before") |
| 423 |
response = self.delete_object(mvalue) |
| 424 |
else: |
| 425 |
if state == "absent": |
| 426 |
self.module.fail_json(msg="This module doesn't not support state:absent yet.") |
| 427 |
self.diff_get_and_save_data("before") |
| 428 |
response = self.create_object() |
| 429 |
self.diff_get_and_save_data("after") |
| 430 |
self.do_exit(response) |
| 431 |
|
| 432 |
def process_partial_crud(self): |
| 433 |
self.allow_diff = True |
| 434 |
argument_specs = self.metadata |
| 435 |
module_name = self.module_level2_name |
| 436 |
params = self.module.params |
| 437 |
version_check = params.get("version_check", VERSION_CHECK) |
| 438 |
bypass_valid = params.get("bypass_validation", False) |
| 439 |
if version_check and not bypass_valid: |
| 440 |
track = [module_name] |
| 441 |
self.check_versioning_mismatch(track, argument_specs.get(module_name, None), params.get(module_name, None)) |
| 442 |
target_url = self.get_target_url() |
| 443 |
api_params = {"url": target_url} |
| 444 |
|
| 445 |
try: |
| 446 |
rc, remote_data = self.conn.send_request("get", [api_params]) |
| 447 |
self.diff_save_data_from_response("before", remote_data) |
| 448 |
if rc == 0: |
| 449 |
if not (self.is_force_update() or self.is_update_required(remote_data)): |
| 450 |
return_msg = "Your FortiManager is already up to date and does not need to be updated. " |
| 451 |
return_msg += "To force update, please add argument proposed_method:update" |
| 452 |
self.diff_save_data_from_response("after", remote_data) |
| 453 |
self.do_final_exit(changed=False, message=return_msg) |
| 454 |
except Exception as e: |
| 455 |
pass |
| 456 |
response = self.update_object(mvalue="", method="set") |
| 457 |
self.diff_get_and_save_data("after") |
| 458 |
self.do_exit(response) |
| 459 |
|
| 460 |
def process_export(self, metadata): |
| 461 |
from ansible_collections.fortinet.fortimanager.plugins.module_utils.exported_schema import ( |
| 462 |
schemas as exported_schema_inventory, |
| 463 |
) |
| 464 |
params = self.module.params |
| 465 |
export_selectors = params["export_playbooks"]["selector"] |
| 466 |
export_path = "./" |
| 467 |
if params["export_playbooks"].get("path", None): |
| 468 |
export_path = params["export_playbooks"]["path"] |
| 469 |
log = open("%s/export.log" % (export_path), "w") |
| 470 |
log.write("Export time: %s\n" % (str(datetime.datetime.now()))) |
| 471 |
|
| 472 |
for selector in export_selectors: |
| 473 |
if selector == "all": |
| 474 |
continue |
| 475 |
export_meta = metadata[selector] |
| 476 |
export_meta_param = export_meta["params"] |
| 477 |
export_meta_urls = export_meta["urls"] |
| 478 |
if ( |
| 479 |
not params["export_playbooks"]["params"] |
| 480 |
or selector not in params["export_playbooks"]["params"] |
| 481 |
): |
| 482 |
self.module.fail_json("parameter export_playbooks->params needs entry:%s" % (selector)) |
| 483 |
if not len(export_meta_urls): |
| 484 |
raise AssertionError("Invalid schema.") |
| 485 |
|
| 486 |
url_tokens = export_meta_urls[0].split("/") |
| 487 |
required_params = list() |
| 488 |
for _param in export_meta_param: |
| 489 |
if "{%s}" % (_param) == url_tokens[-1]: |
| 490 |
continue |
| 491 |
required_params.append(_param) |
| 492 |
for _param in required_params: |
| 493 |
if _param not in params["export_playbooks"]["params"][selector]: |
| 494 |
self.module.fail_json( |
| 495 |
"required parameters for selector %s: %s" |
| 496 |
% (selector, required_params) |
| 497 |
) |
| 498 |
|
| 499 |
if "all" in export_selectors: |
| 500 |
if ( |
| 501 |
"all" not in params["export_playbooks"]["params"] |
| 502 |
or "adom" not in params["export_playbooks"]["params"]["all"] |
| 503 |
): |
| 504 |
self.module.fail_json("required parameters for selector %s: %s" % ("all", ["adom"])) |
| 505 |
|
| 506 |
selectors_to_process = dict() |
| 507 |
for selector in export_selectors: |
| 508 |
if selector == "all": |
| 509 |
continue |
| 510 |
selectors_to_process[selector] = (metadata[selector], self.module.params["export_playbooks"]["params"][selector]) |
| 511 |
if "all" in export_selectors: |
| 512 |
for selector in metadata: |
| 513 |
chosen = True |
| 514 |
if not len(metadata[selector]["urls"]): |
| 515 |
raise AssertionError("Invalid Schema.") |
| 516 |
url_tokens = metadata[selector]["urls"][0].split("/") |
| 517 |
for _param in metadata[selector]["params"]: |
| 518 |
if _param == "adom": |
| 519 |
continue |
| 520 |
elif "{%s}" % (_param) != url_tokens[-1]: |
| 521 |
chosen = False |
| 522 |
break |
| 523 |
if not chosen or selector in selectors_to_process: |
| 524 |
continue |
| 525 |
selectors_to_process[selector] = ( |
| 526 |
metadata[selector], |
| 527 |
self.module.params["export_playbooks"]["params"]["all"], |
| 528 |
) |
| 529 |
process_counter = 1 |
| 530 |
number_selectors = len(selectors_to_process) |
| 531 |
for selector in selectors_to_process: |
| 532 |
self._process_export_per_selector( |
| 533 |
selector, |
| 534 |
selectors_to_process[selector][0], |
| 535 |
selectors_to_process[selector][1], |
| 536 |
log, |
| 537 |
export_path, |
| 538 |
"%s/%s" % (process_counter, number_selectors), |
| 539 |
exported_schema_inventory, |
| 540 |
) |
| 541 |
process_counter += 1 |
| 542 |
self.module.exit_json( |
| 543 |
number_of_selectors=number_selectors, |
| 544 |
number_of_valid_selectors=self._nr_valid_selectors, |
| 545 |
number_of_exported_playbooks=self._nr_exported_playbooks, |
| 546 |
system_infomation=self.system_status, |
| 547 |
) |
| 548 |
|
| 549 |
def is_force_update(self): |
| 550 |
return "proposed_method" in self.module.params and self.module.params["proposed_method"] |
| 551 |
|
| 552 |
def get_mvalue(self): |
| 553 |
|
| 554 |
mvalue = "" |
| 555 |
params = self.module.params |
| 556 |
module_name = self.module_level2_name |
| 557 |
if not (self.module_primary_key and isinstance(params.get(module_name, None), dict)): |
| 558 |
return "" |
| 559 |
if self.module_primary_key.startswith("complex:"): |
| 560 |
mvalue_exec_string = self.module_primary_key[len("complex:"):] |
| 561 |
mvalue_exec_string = mvalue_exec_string.replace("{{module}}", "self.module.params[self.module_level2_name]") |
| 562 |
mvalue = eval(mvalue_exec_string) |
| 563 |
else: |
| 564 |
ansible_format_main_key = get_ansible_format_name(self.module_primary_key) |
| 565 |
if ansible_format_main_key in params[module_name]: |
| 566 |
mvalue = params[module_name][ansible_format_main_key] |
| 567 |
elif self.module_primary_key in params[module_name]: |
| 568 |
mvalue = params[module_name][self.module_primary_key] |
| 569 |
return mvalue |
| 570 |
|
| 571 |
def get_system_status(self): |
| 572 |
status_code, response = self.conn.get_system_status() |
| 573 |
if status_code == 0 and "data" in response: |
| 574 |
return response["data"] |
| 575 |
return {} |
| 576 |
|
| 577 |
def get_propose_method(self, default_method): |
| 578 |
if ( |
| 579 |
"proposed_method" in self.module.params |
| 580 |
and self.module.params["proposed_method"] |
| 581 |
): |
| 582 |
return self.module.params["proposed_method"] |
| 583 |
return default_method |
| 584 |
|
| 585 |
def get_params_in_url(self, s): |
| 586 |
"""Find contents in {}""" |
| 587 |
pattern = r"\{(.*?)\}" |
| 588 |
result = re.findall(pattern, s) |
| 589 |
return result |
| 590 |
|
| 591 |
def get_target_url_template(self, adom_value, url_list): |
| 592 |
target_url = None |
| 593 |
if adom_value is not None and not url_list[0].endswith("{adom}"): |
| 594 |
if adom_value == "global": |
| 595 |
for url in url_list: |
| 596 |
if "/global/" in url and "/adom/{adom}" not in url: |
| 597 |
target_url = url |
| 598 |
break |
| 599 |
elif adom_value: |
| 600 |
for url in url_list: |
| 601 |
if "/adom/{adom}" in url: |
| 602 |
target_url = url |
| 603 |
break |
| 604 |
else: |
| 605 |
|
| 606 |
for url in url_list: |
| 607 |
if "/global/" not in url and "/adom/{adom}" not in url: |
| 608 |
target_url = url |
| 609 |
break |
| 610 |
else: |
| 611 |
target_url = url_list[0] |
| 612 |
if not target_url: |
| 613 |
self.module.fail_json(msg="Please check the value of params: adom") |
| 614 |
return target_url |
| 615 |
|
| 616 |
def get_replaced_url(self, target_url): |
| 617 |
url_params = self.get_params_in_url(target_url) |
| 618 |
for param in url_params: |
| 619 |
token_hint = "{%s}" % (param) |
| 620 |
token = "" |
| 621 |
modified_name = get_ansible_format_name(param) |
| 622 |
modified_token = self.module.params.get(modified_name, None) |
| 623 |
previous_token = self.module.params.get(param, None) |
| 624 |
if modified_token is not None: |
| 625 |
token = modified_token |
| 626 |
elif previous_token is not None: |
| 627 |
token = previous_token |
| 628 |
else: |
| 629 |
self.module.fail_json(msg="Missing input param: %s" % (modified_name)) |
| 630 |
target_url = target_url.replace(token_hint, "%s" % (token)) |
| 631 |
return target_url |
| 632 |
|
| 633 |
def get_target_url(self, mvalue=""): |
| 634 |
adom_value = self.module.params.get("adom", None) |
| 635 |
target_url_template = self.get_target_url_template(adom_value, self.urls_list) |
| 636 |
target_url = self.get_replaced_url(target_url_template) |
| 637 |
|
| 638 |
if mvalue != "" and not target_url_template.endswith("}"): |
| 639 |
if not target_url.endswith("/"): |
| 640 |
target_url += "/" |
| 641 |
target_url += str(mvalue) |
| 642 |
return target_url |
| 643 |
|
| 644 |
def read_object(self, mvalue): |
| 645 |
target_url = self.get_target_url(mvalue) |
| 646 |
params = [{"url": target_url}] |
| 647 |
response = self.conn.send_request("get", params) |
| 648 |
return response |
| 649 |
|
| 650 |
def update_object(self, mvalue, method="update"): |
| 651 |
target_url = self.get_target_url(mvalue) |
| 652 |
bypass_valid = self.module.params.get("bypass_validation", False) is True |
| 653 |
raw_attributes = remove_aliases(self.module.params, self.metadata, bypass_valid) |
| 654 |
raw_attributes = raw_attributes.get(self.module_level2_name, {}) |
| 655 |
params = [{"url": target_url, self.top_level_schema_name: raw_attributes}] |
| 656 |
if self.module.check_mode: |
| 657 |
self.diff_save_after_based_on_playbook() |
| 658 |
self.do_final_exit(changed=True) |
| 659 |
if "revision_note" in self.extra_params: |
| 660 |
params[0]["revision note"] = self.extra_params["revision_note"] |
| 661 |
response = self.conn.send_request(self.get_propose_method(method), params) |
| 662 |
return response |
| 663 |
|
| 664 |
def create_object(self): |
| 665 |
target_url = self.get_target_url() |
| 666 |
bypass_valid = self.module.params.get("bypass_validation", False) is True |
| 667 |
raw_attributes = remove_aliases(self.module.params, self.metadata, bypass_valid) |
| 668 |
raw_attributes = raw_attributes.get(self.module_level2_name, {}) |
| 669 |
params = [{"url": target_url, self.top_level_schema_name: raw_attributes}] |
| 670 |
if self.module.check_mode: |
| 671 |
self.diff_save_after_based_on_playbook() |
| 672 |
self.do_final_exit(changed=True) |
| 673 |
if "revision_note" in self.extra_params: |
| 674 |
params[0]["revision note"] = self.extra_params["revision_note"] |
| 675 |
response = self.conn.send_request(self.get_propose_method("set"), params) |
| 676 |
return response |
| 677 |
|
| 678 |
def delete_object(self, mvalue): |
| 679 |
target_url = self.get_target_url(mvalue) |
| 680 |
params = [{"url": target_url}] |
| 681 |
if self.module.check_mode: |
| 682 |
self.do_final_exit(changed=True) |
| 683 |
return self.conn.send_request("delete", params) |
| 684 |
|
| 685 |
def is_same_subnet(self, object_remote, object_present): |
| 686 |
if isinstance(object_remote, list) and len(object_remote) != 2: |
| 687 |
return False |
| 688 |
tokens = object_present.split("/") |
| 689 |
if len(tokens) != 2: |
| 690 |
return False |
| 691 |
try: |
| 692 |
subnet_number = int(tokens[1]) |
| 693 |
if subnet_number < 0 or subnet_number > 32: |
| 694 |
return False |
| 695 |
remote_subnet_number = sum(bin(int(x)).count("1") for x in object_remote[1].split(".")) |
| 696 |
if object_remote[0] == tokens[0] and remote_subnet_number == subnet_number: |
| 697 |
return True |
| 698 |
except Exception as e: |
| 699 |
return False |
| 700 |
return False |
| 701 |
|
| 702 |
def is_object_difference(self, remote_obj, local_obj): |
| 703 |
for key in local_obj: |
| 704 |
local_value = local_obj[key] |
| 705 |
if local_value is None: |
| 706 |
continue |
| 707 |
if not isinstance(remote_obj, dict): |
| 708 |
return True |
| 709 |
remote_value = remote_obj.get(key, None) |
| 710 |
if remote_value is None: |
| 711 |
return True |
| 712 |
if isinstance(local_value, list): |
| 713 |
try: |
| 714 |
if isinstance(remote_value, list): |
| 715 |
if str(sorted(remote_value)) == str(sorted(local_value)): |
| 716 |
continue |
| 717 |
|
| 718 |
elif len(local_value) == 1: |
| 719 |
if str(remote_value) == str(local_value[0]): |
| 720 |
continue |
| 721 |
except Exception as e: |
| 722 |
return True |
| 723 |
return True |
| 724 |
elif isinstance(local_value, dict): |
| 725 |
if not isinstance(remote_value, dict): |
| 726 |
return True |
| 727 |
elif self.is_object_difference(remote_value, local_value): |
| 728 |
return True |
| 729 |
else: |
| 730 |
value_string = str(local_value) |
| 731 |
if isinstance(remote_value, list): |
| 732 |
if self.is_same_subnet(remote_value, value_string): |
| 733 |
continue |
| 734 |
if " ".join(remote_value) == str(value_string): |
| 735 |
continue |
| 736 |
|
| 737 |
elif len(remote_value) != 1 or str(remote_value[0]) != value_string: |
| 738 |
return True |
| 739 |
elif str(remote_value) != value_string: |
| 740 |
return True |
| 741 |
return False |
| 742 |
|
| 743 |
def is_update_required(self, remote_data): |
| 744 |
object_remote = remote_data["data"] if "data" in remote_data else {} |
| 745 |
bypass_valid = self.module.params.get("bypass_validation", False) |
| 746 |
object_local = remove_aliases(self.module.params, self.metadata, bypass_valid) |
| 747 |
object_local = object_local.get(self.module_level2_name, {}) |
| 748 |
return self.is_object_difference(object_remote, object_local) |
| 749 |
|
| 750 |
def ignore_special_param(self, param_name, remote_data, user_data): |
| 751 |
if param_name in ["ca", "certificate", "cert"]: |
| 752 |
if isinstance(remote_data, list) and len(remote_data): |
| 753 |
remote_data = remote_data[0] |
| 754 |
if isinstance(user_data, list) and len(user_data): |
| 755 |
user_data = user_data[0] |
| 756 |
if remote_data == '"' + str(user_data) + '"': |
| 757 |
return True |
| 758 |
if param_name in ["TTL"]: |
| 759 |
remote_data = str(remote_data) |
| 760 |
user_data = str(user_data) |
| 761 |
if remote_data.split(" ", maxsplit=1)[0] == user_data: |
| 762 |
return True |
| 763 |
return False |
| 764 |
|
| 765 |
def is_version_matched(self, v_ranges): |
| 766 |
if not v_ranges or not self.system_status: |
| 767 |
|
| 768 |
return True, None |
| 769 |
|
| 770 |
sys_version_value = ( |
| 771 |
int(self.system_status["Major"]) * 10000 |
| 772 |
+ int(self.system_status["Minor"]) * 100 |
| 773 |
+ int(self.system_status["Patch"]) |
| 774 |
) |
| 775 |
b_match = False |
| 776 |
for vr in v_ranges: |
| 777 |
min_v = vr[0].split(".") |
| 778 |
min_vn = ( |
| 779 |
int(min_v[0]) * 10000 |
| 780 |
+ int(min_v[1]) * 100 |
| 781 |
+ int(min_v[2]) |
| 782 |
) |
| 783 |
if min_vn > sys_version_value: |
| 784 |
break |
| 785 |
if vr[1] == "": |
| 786 |
b_match = True |
| 787 |
break |
| 788 |
max_v = vr[1].split(".") |
| 789 |
max_vn = ( |
| 790 |
int(max_v[0]) * 10000 |
| 791 |
+ int(max_v[1]) * 100 |
| 792 |
+ int(max_v[2]) |
| 793 |
) |
| 794 |
if max_vn >= sys_version_value: |
| 795 |
b_match = True |
| 796 |
break |
| 797 |
if b_match: |
| 798 |
return True, None |
| 799 |
supported_v = [] |
| 800 |
for vr in v_ranges: |
| 801 |
if vr[1] == "": |
| 802 |
vr_s = ">= %s" % (vr[0]) |
| 803 |
else: |
| 804 |
vr_s = "%s-%s" % (vr[0], (vr[1])) |
| 805 |
supported_v.append(vr_s) |
| 806 |
return ( |
| 807 |
False, |
| 808 |
"Current FortiManager version %s.%s.%s do not support this feature. Supported version range: %s." |
| 809 |
% (self.system_status["Major"], self.system_status["Minor"], self.system_status["Patch"], supported_v), |
| 810 |
) |
| 811 |
|
| 812 |
def check_versioning_mismatch(self, track, schema, params): |
| 813 |
if not params or not schema: |
| 814 |
return |
| 815 |
param_type = schema["type"] if "type" in schema else None |
| 816 |
v_range = schema["v_range"] if "v_range" in schema else None |
| 817 |
matched, checking_message = self.is_version_matched(v_range) |
| 818 |
if not matched: |
| 819 |
param_path = track[0] |
| 820 |
for _param in track[1:]: |
| 821 |
param_path += "-->%s" % (_param) |
| 822 |
self.version_check_warnings.append("param: %s %s" % (param_path, checking_message)) |
| 823 |
if param_type == "dict" and "options" in schema: |
| 824 |
if not isinstance(params, dict): |
| 825 |
raise AssertionError() |
| 826 |
for sub_param_key in params: |
| 827 |
sub_param = params[sub_param_key] |
| 828 |
if sub_param_key in schema["options"]: |
| 829 |
sub_schema = schema["options"][sub_param_key] |
| 830 |
track.append(sub_param_key) |
| 831 |
self.check_versioning_mismatch(track, sub_schema, sub_param) |
| 832 |
del track[-1] |
| 833 |
elif param_type == "list" and "options" in schema: |
| 834 |
if not isinstance(params, list): |
| 835 |
raise AssertionError() |
| 836 |
for grouped_param in params: |
| 837 |
if not isinstance(grouped_param, dict): |
| 838 |
raise AssertionError() |
| 839 |
for sub_param_key in grouped_param: |
| 840 |
sub_param = grouped_param[sub_param_key] |
| 841 |
if sub_param_key in schema["options"]: |
| 842 |
sub_schema = schema["options"][sub_param_key] |
| 843 |
track.append(sub_param_key) |
| 844 |
self.check_versioning_mismatch(track, sub_schema, sub_param) |
| 845 |
del track[-1] |
| 846 |
|
| 847 |
def validate_parameters(self, pvb): |
| 848 |
for blob in pvb: |
| 849 |
attribute_path = blob["attribute_path"] |
| 850 |
pointer = self.module.params |
| 851 |
ignored = False |
| 852 |
for attr in attribute_path: |
| 853 |
if attr not in pointer: |
| 854 |
|
| 855 |
ignored = True |
| 856 |
break |
| 857 |
pointer = pointer[attr] |
| 858 |
if ignored: |
| 859 |
continue |
| 860 |
lambda_expr = blob["lambda"] |
| 861 |
lambda_expr = lambda_expr.replace("$", str(pointer)) |
| 862 |
eval_result = eval(lambda_expr) |
| 863 |
if not eval_result: |
| 864 |
if "fail_action" not in blob or blob["fail_action"] == "warn": |
| 865 |
self.module.warn(blob["hint_message"]) |
| 866 |
else: |
| 867 |
self.module.fail_json(msg=blob["hint_message"]) |
| 868 |
|
| 869 |
def diff_save_after_based_on_playbook(self): |
| 870 |
def get_diff_after(before_data, user_data, metadata=None): |
| 871 |
if before_data is None: |
| 872 |
return user_data |
| 873 |
if user_data is None: |
| 874 |
return before_data |
| 875 |
if not isinstance(metadata, dict): |
| 876 |
metadata = {} |
| 877 |
if is_basic_data_format(before_data): |
| 878 |
if isinstance(user_data, list): |
| 879 |
if len(user_data) == 1 and user_data[0] == before_data: |
| 880 |
return before_data |
| 881 |
return user_data |
| 882 |
if isinstance(before_data, dict): |
| 883 |
if isinstance(user_data, dict): |
| 884 |
after_data = {} |
| 885 |
for param_name in before_data: |
| 886 |
possible_meta_name = param_name.replace("_", "-") |
| 887 |
|
| 888 |
is_sensitive_data = False |
| 889 |
for var_name in [param_name, possible_meta_name]: |
| 890 |
if var_name in metadata and isinstance(metadata[var_name], dict) and metadata[var_name].get("no_log", False): |
| 891 |
before_data[param_name] = "<SENSITIVE_DATA>" |
| 892 |
after_data[param_name] = "<SENSITIVE_DATA>" |
| 893 |
is_sensitive_data = True |
| 894 |
if is_sensitive_data: |
| 895 |
continue |
| 896 |
|
| 897 |
if self.ignore_special_param(param_name, before_data[param_name], user_data.get(param_name, None)): |
| 898 |
after_data[param_name] = before_data[param_name] |
| 899 |
else: |
| 900 |
metadata_next = {} |
| 901 |
if param_name in metadata: |
| 902 |
metadata_next = metadata[param_name] |
| 903 |
elif possible_meta_name in metadata: |
| 904 |
metadata_next = metadata[possible_meta_name] |
| 905 |
if isinstance(metadata_next, dict) and "options" in metadata_next: |
| 906 |
metadata_next = metadata_next["options"] |
| 907 |
after_data[param_name] = get_diff_after(before_data[param_name], user_data.get(param_name, None), metadata_next) |
| 908 |
for param_name in user_data: |
| 909 |
possible_meta_name = param_name.replace("_", "-") |
| 910 |
if param_name not in after_data and possible_meta_name not in after_data: |
| 911 |
after_data[param_name] = user_data[param_name] |
| 912 |
return after_data |
| 913 |
return user_data |
| 914 |
elif isinstance(before_data, list): |
| 915 |
if is_basic_data_format(user_data): |
| 916 |
|
| 917 |
if self.is_same_subnet(before_data, str(user_data)): |
| 918 |
return before_data |
| 919 |
|
| 920 |
if " ".join(before_data) == str(user_data): |
| 921 |
return before_data |
| 922 |
|
| 923 |
if len(before_data) == 1 and str(before_data[0]) == str(user_data): |
| 924 |
return before_data |
| 925 |
elif isinstance(user_data, list): |
| 926 |
if len(user_data) == 0: |
| 927 |
return [] |
| 928 |
elif len(before_data) == 0: |
| 929 |
return user_data |
| 930 |
|
| 931 |
try: |
| 932 |
if str(sorted(before_data)) == str(sorted(user_data)): |
| 933 |
return before_data |
| 934 |
except Exception as e: |
| 935 |
pass |
| 936 |
if isinstance(user_data[0], dict) and isinstance(before_data[0], dict): |
| 937 |
after_data = [] |
| 938 |
for i in range(max(len(before_data), len(user_data))): |
| 939 |
user_data_item = user_data[i] if i < len(user_data) else {} |
| 940 |
before_data_item = before_data[i] if i < len(before_data) else None |
| 941 |
after_data.append(get_diff_after(before_data_item, user_data_item, metadata)) |
| 942 |
return after_data |
| 943 |
return user_data |
| 944 |
return before_data |
| 945 |
|
| 946 |
if not (self.allow_diff and (self.module._diff or self.module.check_mode)): |
| 947 |
return |
| 948 |
before_data = self.diff_data["before"] |
| 949 |
bypass_valid = self.module.params.get("bypass_validation", False) |
| 950 |
api_format_params = remove_aliases(self.module.params, self.metadata, bypass_valid) |
| 951 |
api_format_params = api_format_params.get(self.module_level2_name, {}) |
| 952 |
ansible_format_params = get_ansible_format_params(api_format_params) |
| 953 |
metadata = self.metadata.get(self.module_level2_name, {}).get("options", {}) |
| 954 |
if isinstance(before_data, list) and len(before_data) > 0 and isinstance(before_data[0], dict): |
| 955 |
if isinstance(ansible_format_params, dict): |
| 956 |
ansible_format_params = [ansible_format_params] |
| 957 |
self.diff_data["after"] = get_diff_after(before_data, ansible_format_params, metadata) |
| 958 |
|
| 959 |
def diff_save_data_from_response(self, state, response): |
| 960 |
if self.allow_diff and (self.module._diff or self.module.check_mode): |
| 961 |
api_format_data = response["data"] if "data" in response else {} |
| 962 |
if not api_format_data: |
| 963 |
api_format_data = {} |
| 964 |
ansible_format_data = get_ansible_format_params(api_format_data) |
| 965 |
self.diff_data[state] = ansible_format_data |
| 966 |
|
| 967 |
def diff_get_and_save_data(self, state): |
| 968 |
if self.allow_diff and (self.module._diff or self.module.check_mode): |
| 969 |
mvalue = self.get_mvalue() |
| 970 |
target_url = self.get_target_url(mvalue) |
| 971 |
api_params = [{"url": target_url}] |
| 972 |
rc, response = self.conn.send_request("get", api_params) |
| 973 |
self.diff_save_data_from_response(state, response) |
| 974 |
|
| 975 |
def __fix_remote_object_internal(self, robject, module_schema, log): |
| 976 |
if not isinstance(robject, dict): |
| 977 |
return True |
| 978 |
need_bypass = False |
| 979 |
keys_to_delete = list() |
| 980 |
for key in robject: |
| 981 |
value = robject[key] |
| 982 |
|
| 983 |
if key not in module_schema: |
| 984 |
keys_to_delete.append(key) |
| 985 |
continue |
| 986 |
|
| 987 |
attr_schema = module_schema[key] |
| 988 |
attr_type = attr_schema["type"] |
| 989 |
if attr_type in ["str", "int"]: |
| 990 |
|
| 991 |
if isinstance(value, list): |
| 992 |
if len(value) == 1: |
| 993 |
robject[key] = value[0] |
| 994 |
log.write("\tfix list-to-atomic key:%s\n" % (key)) |
| 995 |
else: |
| 996 |
need_bypass = True |
| 997 |
elif isinstance(value, dict): |
| 998 |
need_bypass = True |
| 999 |
if not value or value == "null": |
| 1000 |
log.write("\tdelete empty key:%s\n" % (key)) |
| 1001 |
keys_to_delete.append(key) |
| 1002 |
elif attr_type == "dict": |
| 1003 |
if "options" in attr_schema and isinstance(value, dict): |
| 1004 |
need_bypass |= self.__fix_remote_object_internal( |
| 1005 |
value, attr_schema["options"], log |
| 1006 |
) |
| 1007 |
else: |
| 1008 |
need_bypass = True |
| 1009 |
if not value or value == "null": |
| 1010 |
log.write("\tdelete empty key:%s\n" % (key)) |
| 1011 |
keys_to_delete.append(key) |
| 1012 |
elif attr_type == "list": |
| 1013 |
if "options" in attr_schema and isinstance(value, list): |
| 1014 |
for sub_value in value: |
| 1015 |
need_bypass |= self.__fix_remote_object_internal( |
| 1016 |
sub_value, attr_schema["options"], log |
| 1017 |
) |
| 1018 |
else: |
| 1019 |
need_bypass = True |
| 1020 |
if ( |
| 1021 |
isinstance(value, list) |
| 1022 |
and not len(value) |
| 1023 |
or value == "null" |
| 1024 |
or not value |
| 1025 |
): |
| 1026 |
log.write("\tdelete empty key:%s\n" % (key)) |
| 1027 |
keys_to_delete.append(key) |
| 1028 |
else: |
| 1029 |
continue |
| 1030 |
for key in keys_to_delete: |
| 1031 |
log.write("\tdelete unrecognized key:%s\n" % (key)) |
| 1032 |
del robject[key] |
| 1033 |
return need_bypass |
| 1034 |
|
| 1035 |
def __append_whiteblank_per_line(self, blob, num_of_blank): |
| 1036 |
ret = " " * num_of_blank |
| 1037 |
ret += blob.replace("\n", "\n%s" % (" " * num_of_blank)) |
| 1038 |
return ret |
| 1039 |
|
| 1040 |
def _generate_playbook(self, counter, export_path, selector, robject, state_present, |
| 1041 |
need_bypass, url_params, params_schema, log): |
| 1042 |
prefix_text = """- name: Exported Playbook |
| 1043 |
hosts: fortimanagers |
| 1044 |
connection: httpapi |
| 1045 |
collections: |
| 1046 |
- fortinet.fortimanager |
| 1047 |
vars: |
| 1048 |
ansible_httpapi_use_ssl: true |
| 1049 |
ansible_httpapi_validate_certs: false |
| 1050 |
ansible_httpapi_port: 443 |
| 1051 |
tasks: |
| 1052 |
""" |
| 1053 |
with open("%s/%s_%s.yml" % (export_path, selector, counter), "w") as f: |
| 1054 |
f.write(prefix_text) |
| 1055 |
f.write(" - name: exported config for %s\n" % (selector)) |
| 1056 |
f.write(" fmgr_%s:\n" % (selector)) |
| 1057 |
if need_bypass: |
| 1058 |
f.write(" bypass_validation: true\n") |
| 1059 |
if state_present: |
| 1060 |
f.write(" state: present\n") |
| 1061 |
for url_param_key in params_schema: |
| 1062 |
if url_param_key not in url_params: |
| 1063 |
continue |
| 1064 |
url_param_value = url_params[url_param_key] |
| 1065 |
f.write(" %s: %s\n" % (url_param_key, url_param_value)) |
| 1066 |
f.write(" %s:\n" % (selector)) |
| 1067 |
f.write(self.__append_whiteblank_per_line(yaml.dump(robject), 8)) |
| 1068 |
log.write( |
| 1069 |
"\texported playbook: %s/%s_%s.yml\n" % (export_path, selector, counter) |
| 1070 |
) |
| 1071 |
self._nr_exported_playbooks += 1 |
| 1072 |
|
| 1073 |
def _process_export_response(self, selector, response, schema_invt, log, |
| 1074 |
export_path, url_params, params_schema): |
| 1075 |
response_code = response[0] |
| 1076 |
response_data = response[1] |
| 1077 |
if response_code != 0 or "data" not in response_data: |
| 1078 |
log.write("\tno configuration data found\n") |
| 1079 |
return |
| 1080 |
if selector not in schema_invt: |
| 1081 |
log.write("\trequested object has no corresponding ansible module\n") |
| 1082 |
return |
| 1083 |
state_present = schema_invt[selector]["stated"] |
| 1084 |
module_schema = schema_invt[selector]["options"] |
| 1085 |
remote_objects = response_data["data"] |
| 1086 |
counter = 0 |
| 1087 |
if isinstance(remote_objects, list): |
| 1088 |
for remote_object in remote_objects: |
| 1089 |
need_bypass = self.__fix_remote_object_internal(remote_object, module_schema, log) |
| 1090 |
self._generate_playbook(counter, export_path, selector, remote_object, |
| 1091 |
state_present, need_bypass, url_params, params_schema, log) |
| 1092 |
counter += 1 |
| 1093 |
elif isinstance(remote_objects, dict): |
| 1094 |
need_bypass = self.__fix_remote_object_internal(remote_objects, module_schema, log) |
| 1095 |
self._generate_playbook(counter, export_path, selector, remote_objects, state_present, |
| 1096 |
need_bypass, url_params, params_schema, log) |
| 1097 |
counter += 1 |
| 1098 |
if not counter: |
| 1099 |
self._nr_valid_selectors += 1 |
| 1100 |
|
| 1101 |
def _process_export_per_selector(self, selector, schema, param, log, export_path, process, schema_invt): |
| 1102 |
|
| 1103 |
url = None |
| 1104 |
export_urls = schema["urls"] |
| 1105 |
if "adom" in param and not export_urls[0].endswith("{adom}"): |
| 1106 |
if param["adom"] == "global": |
| 1107 |
for _url in export_urls: |
| 1108 |
if "/global/" in _url and "/adom/{adom}/" not in _url: |
| 1109 |
url = _url |
| 1110 |
break |
| 1111 |
else: |
| 1112 |
for _url in export_urls: |
| 1113 |
if "/adom/{adom}/" in _url: |
| 1114 |
url = _url |
| 1115 |
break |
| 1116 |
if not url: |
| 1117 |
url = export_urls[0] |
| 1118 |
_param_applied = list() |
| 1119 |
for _param_key in param: |
| 1120 |
_param_value = param[_param_key] |
| 1121 |
if _param_key == "adom" and _param_value.lower() == "global": |
| 1122 |
continue |
| 1123 |
token_hint = "/%s/{%s}" % (_param_key, _param_key) |
| 1124 |
token = "/%s/%s" % (_param_key, _param_value) |
| 1125 |
if token_hint in url: |
| 1126 |
_param_applied.append(_param_key) |
| 1127 |
url = url.replace(token_hint, token) |
| 1128 |
for _param_key in param: |
| 1129 |
if _param_key in _param_applied: |
| 1130 |
continue |
| 1131 |
if _param_key == "adom" and _param_value.lower() == "global": |
| 1132 |
continue |
| 1133 |
token_hint = "{%s}" % (_param_key) |
| 1134 |
token = param[_param_key] |
| 1135 |
url = url.replace(token_hint, token) |
| 1136 |
tokens = url.split("/") |
| 1137 |
if tokens[-1].startswith("{") and tokens[-1].endswith("}"): |
| 1138 |
new_url = "" |
| 1139 |
for token in tokens[:-1]: |
| 1140 |
new_url += "/%s" % (token) |
| 1141 |
new_url = new_url.replace("//", "/") |
| 1142 |
url = new_url |
| 1143 |
unresolved_parameter = False |
| 1144 |
tokens = url.split("/") |
| 1145 |
for token in tokens: |
| 1146 |
if token.startswith("{") and token.endswith("}"): |
| 1147 |
unresolved_parameter = True |
| 1148 |
break |
| 1149 |
log.write("[%s]exporting: %s\n" % (process, selector)) |
| 1150 |
log.write("\turl: %s\n" % (url)) |
| 1151 |
if unresolved_parameter: |
| 1152 |
log.write("\t unknown parameter, skipped!\n") |
| 1153 |
return |
| 1154 |
response = self.conn.send_request("get", [{"url": url}]) |
| 1155 |
self._process_export_response(selector, response, schema_invt, log, export_path, param, schema["params"]) |
| 1156 |
|
| 1157 |
def do_exit(self, response, changed=True): |
| 1158 |
rc, response_data = response |
| 1159 |
result = dict() |
| 1160 |
result["response_data"] = response_data.get("data", []) |
| 1161 |
result["response_message"] = "" |
| 1162 |
if "status" in response_data: |
| 1163 |
if "code" in response_data["status"]: |
| 1164 |
result["response_code"] = response_data["status"]["code"] |
| 1165 |
if "message" in response_data["status"]: |
| 1166 |
result["response_message"] = response_data["status"]["message"] |
| 1167 |
if "url" in response_data: |
| 1168 |
result["request_url"] = response_data["url"] |
| 1169 |
|
| 1170 |
if response_data["url"] == "/sys/hitcount": |
| 1171 |
if isinstance(result["response_data"], list) and len(result["response_data"]) == 0: |
| 1172 |
result["response_data"] = dict() |
| 1173 |
if "taskid" in response_data and isinstance(result["response_data"], dict) \ |
| 1174 |
and "task" not in result["response_data"]: |
| 1175 |
result["response_data"]["task"] = response_data["taskid"] |
| 1176 |
self.do_final_exit(rc=rc, result=result, changed=changed) |
| 1177 |
|
| 1178 |
def do_final_exit(self, rc=0, result=None, changed=True, message=""): |
| 1179 |
|
| 1180 |
failed = rc != 0 |
| 1181 |
if changed: |
| 1182 |
changed = rc == 0 |
| 1183 |
if changed and self.allow_diff and (self.module._diff or self.module.check_mode): |
| 1184 |
changed = self.diff_data["before"] != self.diff_data["after"] |
| 1185 |
if result is None: |
| 1186 |
result = {} |
| 1187 |
if "response_code" in result: |
| 1188 |
if self.module.params.get("rc_failed", []): |
| 1189 |
for rc_code in self.module.params["rc_failed"]: |
| 1190 |
if str(result["response_code"]) == str(rc_code): |
| 1191 |
failed = True |
| 1192 |
result["result_code_overriding"] = "rc code:%s is overridden to failure" % (rc_code) |
| 1193 |
elif self.module.params.get("rc_succeeded", []): |
| 1194 |
for rc_code in self.module.params["rc_succeeded"]: |
| 1195 |
if str(result["response_code"]) == str(rc_code): |
| 1196 |
failed = False |
| 1197 |
result["result_code_overriding"] = "rc code:%s is overridden to success" % (rc_code) |
| 1198 |
if self.system_status: |
| 1199 |
result["system_information"] = self.system_status |
| 1200 |
return_response = {"rc": rc, "failed": failed, "changed": changed, "meta": result} |
| 1201 |
if message: |
| 1202 |
return_response["message"] = message |
| 1203 |
if self.module.check_mode: |
| 1204 |
return_response["message"] = "Using check mode." |
| 1205 |
if message: |
| 1206 |
return_response["message"] += " " + message |
| 1207 |
if len(self.version_check_warnings) and self.module.params.get("version_check", VERSION_CHECK): |
| 1208 |
version_check_warning = {} |
| 1209 |
version_check_warning["mismatches"] = self.version_check_warnings |
| 1210 |
if self.system_status: |
| 1211 |
version_check_warning["system_version"] = "v%s.%s.%s" % ( |
| 1212 |
self.system_status["Major"], |
| 1213 |
self.system_status["Minor"], |
| 1214 |
self.system_status["Patch"], |
| 1215 |
) |
| 1216 |
self.module.warn( |
| 1217 |
"Some parameters in the playbook may not be supported by the current FortiManager version. " |
| 1218 |
"To see which parameters are not available, check version_check_warning in the output. " |
| 1219 |
"This message is only a suggestion. You can ignore this warning by setting version_check to False." |
| 1220 |
) |
| 1221 |
return_response["version_check_warning"] = version_check_warning |
| 1222 |
if self.allow_diff and self.module._diff: |
| 1223 |
self.diff_data["before"] = {"data": self.diff_data["before"]} |
| 1224 |
self.diff_data["after"] = {"data": self.diff_data["after"]} |
| 1225 |
return_response["diff"] = self.diff_data |
| 1226 |
self.module.exit_json(**return_response) |