Debian Codegraph @

ansible_collections/theforeman/foreman/plugins/module_utils/foreman_helper.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # (c) Matthias Dellweg (ATIX AG) 2017
3
4 # pylint: disable=raise-missing-from
5 # pylint: disable=super-with-arguments
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10
11 import hashlib
12 import json
13 import os
14 import operator
15 import re
16 import traceback
17
18 from contextlib import contextmanager
19
20 from collections import defaultdict
21 from functools import wraps
22
23 from ansible.module_utils.basic import AnsibleModule, missing_required_lib, env_fallback
24 from ansible.module_utils.common.text.converters import to_bytes, to_native
25 from ansible.module_utils import six
26
27 try:
28 from ansible_collections.theforeman.foreman.plugins.module_utils._version import LooseVersion
29 except ImportError:
30 from plugins.module_utils._version import LooseVersion
31
32 try:
33 try:
34 from ansible_collections.theforeman.foreman.plugins.module_utils import _apypie as apypie
35 except ImportError:
36 from plugins.module_utils import _apypie as apypie
37 import requests.exceptions
38 HAS_APYPIE = True
39 APYPIE_IMP_ERR = None
40 inflector = apypie.Inflector()
41 except ImportError:
42 HAS_APYPIE = False
43 APYPIE_IMP_ERR = traceback.format_exc()
44
45 try:
46 import yaml
47 HAS_PYYAML = True
48 PYYAML_IMP_ERR = None
49 except ImportError:
50 HAS_PYYAML = False
51 PYYAML_IMP_ERR = traceback.format_exc()
52
53 parameter_foreman_spec = dict(
54 id=dict(invisible=True),
55 name=dict(required=True),
56 value=dict(type='raw', required=True),
57 parameter_type=dict(default='string', choices=['string', 'boolean', 'integer', 'real', 'array', 'hash', 'yaml', 'json']),
58 hidden_value=dict(type='bool'),
59 )
60
61 parameter_ansible_spec = {k: v for (k, v) in parameter_foreman_spec.items() if k != 'id'}
62
63 _PLUGIN_RESOURCES = {
64 'ansible': 'ansible_roles',
65 'discovery': 'discovery_rules',
66 'katello': 'subscriptions',
67 'openscap': 'scap_contents',
68 'remote_execution': 'remote_execution_features',
69 'scc_manager': 'scc_accounts',
70 'snapshot_management': 'snapshots',
71 'templates': 'templates',
72 }
73
74 ENTITY_KEYS = dict(
75 hostgroups='title',
76 locations='title',
77 operatingsystems='title',
78 # TODO: Organizations should be search by title (as foreman allows nested orgs) but that's not the case ATM.
79 # Applying this will need to record a lot of tests that is out of scope for the moment.
80 # organizations='title',
81 scap_contents='title',
82 users='login',
83 )
84
85 PER_PAGE = 2 << 31
86
87
88 class NoEntity(object):
89 pass
90
91
92 def _exception2fail_json(msg='Generic failure: {0}'):
93 """
94 Decorator to convert Python exceptions into Ansible errors that can be reported to the user.
95 """
96
97 def decor(f):
98 @wraps(f)
99 def inner(self, *args, **kwargs):
100 try:
101 return f(self, *args, **kwargs)
102 except Exception as e:
103 err_msg = "{0}: {1}".format(e.__class__.__name__, to_native(e))
104 self.fail_from_exception(e, msg.format(err_msg))
105 return inner
106 return decor
107
108
109 def _check_patch_needed(introduced_version=None, fixed_version=None, plugins=None):
110 """
111 Decorator to check whether a specific apidoc patch is required.
112
113 :param introduced_version: The version of Foreman the API bug was introduced.
114 :type introduced_version: str, optional
115 :param fixed_version: The version of Foreman the API bug was fixed.
116 :type fixed_version: str, optional
117 :param plugins: Which plugins are required for this patch.
118 :type plugins: list, optional
119 """
120
121 def decor(f):
122 @wraps(f)
123 def inner(self, *args, **kwargs):
124 if plugins is not None and not all(self.has_plugin(plugin) for plugin in plugins):
125 return
126
127 if fixed_version is not None and self.foreman_version >= LooseVersion(fixed_version):
128 return
129
130 if introduced_version is not None and self.foreman_version < LooseVersion(introduced_version):
131 return
132
133 return f(self, *args, **kwargs)
134 return inner
135 return decor
136
137
138 class KatelloMixin():
139 """
140 Katello Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with Katello entities.
141
142 This includes:
143
144 * add a required ``organization`` parameter to the module
145 * add Katello to the list of required plugins
146 """
147
148 def __init__(self, **kwargs):
149 foreman_spec = dict(
150 organization=dict(type='entity', required=True),
151 )
152 foreman_spec.update(kwargs.pop('foreman_spec', {}))
153 required_plugins = kwargs.pop('required_plugins', [])
154 required_plugins.append(('katello', ['*']))
155 super(KatelloMixin, self).__init__(foreman_spec=foreman_spec, required_plugins=required_plugins, **kwargs)
156
157
158 class TaxonomyMixin(object):
159 """
160 Taxonomy Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with taxonomic entities.
161
162 This adds optional ``organizations`` and ``locations`` parameters to the module.
163 """
164
165 def __init__(self, **kwargs):
166 foreman_spec = dict(
167 organizations=dict(type='entity_list'),
168 locations=dict(type='entity_list'),
169 )
170 foreman_spec.update(kwargs.pop('foreman_spec', {}))
171 super(TaxonomyMixin, self).__init__(foreman_spec=foreman_spec, **kwargs)
172
173
174 class ParametersMixinBase(object):
175 """
176 Base Class for the Parameters Mixins.
177
178 Provides a function to verify no duplicate parameters are set.
179 """
180
181 def validate_parameters(self):
182 parameters = self.foreman_params.get('parameters')
183 if parameters is not None:
184 parameter_names = [param['name'] for param in parameters]
185 duplicate_params = set([x for x in parameter_names if parameter_names.count(x) > 1])
186 if duplicate_params:
187 self.fail_json(msg="There are duplicate keys in 'parameters': {0}.".format(duplicate_params))
188
189
190 class ParametersMixin(ParametersMixinBase):
191 """
192 Parameters Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with entities that support parameters.
193
194 This allows to submit parameters to Foreman in the same request as modifying the main entity, thus making the parameters
195 available to any action that might be triggered when the entity is saved.
196
197 By default, parametes are submited to the API using the ``<entity_name>_parameters_attributes`` key.
198 If you need to override this, set the ``PARAMETERS_FLAT_NAME`` attribute to the key that shall be used instead.
199
200 This adds optional ``parameters`` parameter to the module. It also enhances the ``run()`` method to properly handle the
201 provided parameters.
202 """
203
204 def __init__(self, **kwargs):
205 self.entity_name = kwargs.pop('entity_name', self.entity_name_from_class)
206 parameters_flat_name = getattr(self, "PARAMETERS_FLAT_NAME", None) or '{0}_parameters_attributes'.format(self.entity_name)
207 foreman_spec = dict(
208 parameters=dict(type='list', elements='dict', options=parameter_ansible_spec, flat_name=parameters_flat_name),
209 )
210 foreman_spec.update(kwargs.pop('foreman_spec', {}))
211 super(ParametersMixin, self).__init__(foreman_spec=foreman_spec, **kwargs)
212
213 self.validate_parameters()
214
215 def run(self, **kwargs):
216 entity = self.lookup_entity('entity', params={'show_hidden_parameters': True})
217 if not self.desired_absent:
218 if entity and 'parameters' in entity:
219 entity['parameters'] = parameters_list_to_str_list(entity['parameters'])
220 parameters = self.foreman_params.get('parameters')
221 if parameters is not None:
222 self.foreman_params['parameters'] = parameters_list_to_str_list(parameters)
223
224 return super(ParametersMixin, self).run(**kwargs)
225
226
227 class NestedParametersMixin(ParametersMixinBase):
228 """
229 Nested Parameters Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with entities that support parameters,
230 but require them to be managed in separate API requests.
231
232 This adds optional ``parameters`` parameter to the module. It also enhances the ``run()`` method to properly handle the
233 provided parameters.
234 """
235
236 def __init__(self, **kwargs):
237 foreman_spec = dict(
238 parameters=dict(type='nested_list', foreman_spec=parameter_foreman_spec),
239 )
240 foreman_spec.update(kwargs.pop('foreman_spec', {}))
241 super(NestedParametersMixin, self).__init__(foreman_spec=foreman_spec, **kwargs)
242
243 self.validate_parameters()
244
245 def run(self, **kwargs):
246 new_entity = super(NestedParametersMixin, self).run(**kwargs)
247 if new_entity:
248 scope = {'{0}_id'.format(self.entity_name): new_entity['id']}
249 self.ensure_scoped_parameters(scope)
250 return new_entity
251
252 def ensure_scoped_parameters(self, scope):
253 parameters = self.foreman_params.get('parameters')
254 if parameters is not None:
255 entity = self.lookup_entity('entity')
256 if self.state == 'present' or (self.state == 'present_with_defaults' and entity is None):
257 if entity:
258 current_parameters = {parameter['name']: parameter for parameter in self.list_resource('parameters', params=scope)}
259 else:
260 current_parameters = {}
261 desired_parameters = {parameter['name']: parameter for parameter in parameters}
262
263 for name in desired_parameters:
264 desired_parameter = desired_parameters[name]
265 desired_parameter['value'] = parameter_value_to_str(desired_parameter['value'], desired_parameter['parameter_type'])
266 current_parameter = current_parameters.pop(name, None)
267 if current_parameter:
268 if 'hidden_value?' in current_parameter:
269 current_parameter['hidden_value'] = current_parameter.pop('hidden_value?')
270 if 'parameter_type' not in current_parameter:
271 current_parameter['parameter_type'] = 'string'
272 current_parameter['value'] = parameter_value_to_str(current_parameter['value'], current_parameter['parameter_type'])
273 self.ensure_entity(
274 'parameters', desired_parameter, current_parameter, state="present", foreman_spec=parameter_foreman_spec, params=scope)
275 for current_parameter in current_parameters.values():
276 self.ensure_entity(
277 'parameters', None, current_parameter, state="absent", foreman_spec=parameter_foreman_spec, params=scope)
278
279
280 class HostMixin(ParametersMixin):
281 """
282 Host Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with host-related entities (Hosts, Hostgroups).
283
284 This adds many optional parameters that are specific to Hosts and Hostgroups to the module.
285 It also includes :class:`ParametersMixin`.
286 """
287
288 def __init__(self, **kwargs):
289 foreman_spec = dict(
290 compute_resource=dict(type='entity'),
291 compute_profile=dict(type='entity'),
292 domain=dict(type='entity'),
293 subnet=dict(type='entity'),
294 subnet6=dict(type='entity', resource_type='subnets'),
295 root_pass=dict(no_log=True),
296 realm=dict(type='entity'),
297 architecture=dict(type='entity'),
298 operatingsystem=dict(type='entity'),
299 medium=dict(aliases=['media'], type='entity'),
300 ptable=dict(type='entity'),
301 pxe_loader=dict(choices=['PXELinux BIOS', 'PXELinux UEFI', 'Grub UEFI', 'Grub2 BIOS', 'Grub2 ELF',
302 'Grub2 UEFI', 'Grub2 UEFI SecureBoot', 'Grub2 UEFI HTTP', 'Grub2 UEFI HTTPS',
303 'Grub2 UEFI HTTPS SecureBoot', 'iPXE Embedded', 'iPXE UEFI HTTP', 'iPXE Chain BIOS', 'iPXE Chain UEFI', 'None']),
304 environment=dict(type='entity'),
305 puppetclasses=dict(type='entity_list', resolve=False),
306 config_groups=dict(type='entity_list'),
307 puppet_proxy=dict(type='entity', resource_type='smart_proxies'),
308 puppet_ca_proxy=dict(type='entity', resource_type='smart_proxies'),
309 openscap_proxy=dict(type='entity', resource_type='smart_proxies'),
310 content_source=dict(type='entity', scope=['organization'], resource_type='smart_proxies'),
311 lifecycle_environment=dict(type='entity', scope=['organization']),
312 kickstart_repository=dict(type='entity', scope=['organization'], optional_scope=['lifecycle_environment', 'content_view'],
313 resource_type='repositories'),
314 content_view=dict(type='entity', scope=['organization'], optional_scope=['lifecycle_environment']),
315 activation_keys=dict(no_log=False),
316 )
317 foreman_spec.update(kwargs.pop('foreman_spec', {}))
318 required_plugins = kwargs.pop('required_plugins', []) + [
319 ('katello', ['activation_keys', 'content_source', 'lifecycle_environment', 'kickstart_repository', 'content_view']),
320 ('openscap', ['openscap_proxy']),
321 ]
322 mutually_exclusive = kwargs.pop('mutually_exclusive', []) + [['medium', 'kickstart_repository']]
323 super(HostMixin, self).__init__(foreman_spec=foreman_spec, required_plugins=required_plugins, mutually_exclusive=mutually_exclusive, **kwargs)
324
325 def run(self, **kwargs):
326 entity = self.lookup_entity('entity')
327
328 if not self.desired_absent:
329 if 'activation_keys' in self.foreman_params:
330 if 'parameters' not in self.foreman_params:
331 parameters = [param for param in (entity or {}).get('parameters', []) if param['name'] != 'kt_activation_keys']
332 else:
333 parameters = self.foreman_params['parameters']
334 ak_param = {'name': 'kt_activation_keys', 'parameter_type': 'string', 'value': self.foreman_params.pop('activation_keys')}
335 self.foreman_params['parameters'] = parameters + [ak_param]
336 elif 'parameters' in self.foreman_params and entity is not None:
337 current_ak_param = next((param for param in entity.get('parameters') if param['name'] == 'kt_activation_keys'), None)
338 desired_ak_param = next((param for param in self.foreman_params['parameters'] if param['name'] == 'kt_activation_keys'), None)
339 if current_ak_param and desired_ak_param is None:
340 self.foreman_params['parameters'].append(current_ak_param)
341
342 self.validate_parameters()
343
344 return super(HostMixin, self).run(**kwargs)
345
346
347 class ForemanAnsibleModule(AnsibleModule):
348 """ Baseclass for all foreman related Ansible modules.
349 It handles connection parameters and adds the concept of the `foreman_spec`.
350 This adds automatic entities resolution based on provided attributes/ sub entities options.
351
352 It adds the following options to foreman_spec 'entity' and 'entity_list' types:
353
354 * search_by (str): Field used to search the sub entity. Defaults to 'name' unless `parent` was set, in which case it defaults to `title`.
355 * search_operator (str): Operator used to search the sub entity. Defaults to '='. For fuzzy search use '~'.
356 * resource_type (str): Resource type used to build API resource PATH. Defaults to pluralized entity key.
357 * resolve (boolean): Defaults to 'True'. If set to false, the sub entity will not be resolved automatically
358 * ensure (boolean): Defaults to 'True'. If set to false, it will be removed before sending data to the foreman server.
359 """
360
361 def __init__(self, **kwargs):
362 # State recording for changed and diff reporting
363 self._changed = False
364 self._before = defaultdict(list)
365 self._after = defaultdict(list)
366 self._after_full = defaultdict(list)
367
368 self.foreman_spec, gen_args = _foreman_spec_helper(kwargs.pop('foreman_spec', {}))
369 argument_spec = dict(
370 server_url=dict(required=True, fallback=(env_fallback, ['FOREMAN_SERVER_URL', 'FOREMAN_SERVER', 'FOREMAN_URL'])),
371 username=dict(required=False, fallback=(env_fallback, ['FOREMAN_USERNAME', 'FOREMAN_USER'])),
372 password=dict(required=False, no_log=True, fallback=(env_fallback, ['FOREMAN_PASSWORD'])),
373 oauth1_consumer_key=dict(required=False, no_log=True, fallback=(env_fallback, ['FOREMAN_OAUTH1_CONSUMER_KEY'])),
374 oauth1_consumer_secret=dict(required=False, no_log=True, fallback=(env_fallback, ['FOREMAN_OAUTH1_CONSUMER_SECRET'])),
375 validate_certs=dict(type='bool', default=True, fallback=(env_fallback, ['FOREMAN_VALIDATE_CERTS'])),
376 use_gssapi=dict(type='bool', default=False, fallback=(env_fallback, ['FOREMAN_USE_GSSAPI'])),
377 ca_path=dict(type='path', default=None, fallback=(env_fallback, ['FOREMAN_CA_PATH'])),
378 )
379 argument_spec.update(gen_args)
380 argument_spec.update(kwargs.pop('argument_spec', {}))
381 supports_check_mode = kwargs.pop('supports_check_mode', True)
382 required_if = kwargs.pop('required_if', [])
383 required_if.append(('use_gssapi', False, ('username', 'oauth1_consumer_key'), True))
384 required_together = kwargs.pop('required_together', [])
385 required_together.append(('username', 'password'))
386 required_together.append(('oauth1_consumer_key', 'oauth1_consumer_secret'))
387
388 self.required_plugins = kwargs.pop('required_plugins', [])
389
390 super(ForemanAnsibleModule, self).__init__(argument_spec=argument_spec, supports_check_mode=supports_check_mode,
391 required_if=required_if, required_together=required_together, **kwargs)
392
393 aliases = {alias for arg in argument_spec.values() for alias in arg.get('aliases', [])}
394 self.foreman_params = _recursive_dict_without_none(self.params, aliases)
395
396 self.check_requirements()
397
398 self._foremanapi_server_url = self.foreman_params.pop('server_url')
399 self._foremanapi_username = self.foreman_params.pop('username', None)
400 self._foremanapi_password = self.foreman_params.pop('password', None)
401 self._foremanapi_oauth1_consumer_key = self.foreman_params.pop('oauth1_consumer_key', None)
402 self._foremanapi_oauth1_consumer_secret = self.foreman_params.pop('oauth1_consumer_secret', None)
403 self._foremanapi_validate_certs = self.foreman_params.pop('validate_certs')
404 self._foremanapi_ca_path = self.foreman_params.pop('ca_path', None)
405 self._foremanapi_use_gssapi = self.foreman_params.pop('use_gssapi')
406
407 if self._foremanapi_server_url.lower().startswith('http://'):
408 self.warn("You have configured a plain HTTP server URL. All communication will happen unencrypted.")
409 elif not self._foremanapi_server_url.lower().startswith('https://'):
410 self.fail_json(msg="The server URL needs to be either HTTPS or HTTP!")
411
412 self.task_timeout = 60
413
414 self._thin_default = False
415 self.state = 'undefined'
416
417 @contextmanager
418 def api_connection(self):
419 """
420 Execute a given code block after connecting to the API.
421
422 When the block has finished, call :func:`exit_json` to report that the module has finished to Ansible.
423 """
424
425 self.connect()
426 yield
427 self.exit_json()
428
429 @property
430 def changed(self):
431 return self._changed
432
433 def set_changed(self):
434 self._changed = True
435
436 def _patch_host_update(self):
437 _host_methods = self.foremanapi.apidoc['docs']['resources']['hosts']['methods']
438
439 _host_update = next(x for x in _host_methods if x['name'] == 'update')
440 for param in ['location_id', 'organization_id']:
441 _host_update_taxonomy_param = next((x for x in _host_update['params'] if x['name'] == param), None)
442 if _host_update_taxonomy_param is not None:
443 _host_update['params'].remove(_host_update_taxonomy_param)
444
445 @_check_patch_needed(fixed_version='2.2.0', plugins=['remote_execution'])
446 def _patch_subnet_rex_api(self):
447 """
448 This is a workaround for the broken subnet apidoc in foreman remote execution.
449 See https://projects.theforeman.org/issues/19086 and https://projects.theforeman.org/issues/30651
450 """
451
452 _subnet_rex_proxies_parameter = {
453 u'validations': [],
454 u'name': u'remote_execution_proxy_ids',
455 u'show': True,
456 u'description': u'\n<p>Remote Execution Proxy IDs</p>\n',
457 u'required': False,
458 u'allow_nil': True,
459 u'allow_blank': False,
460 u'full_name': u'subnet[remote_execution_proxy_ids]',
461 u'expected_type': u'array',
462 u'metadata': None,
463 u'validator': u'',
464 }
465 _subnet_methods = self.foremanapi.apidoc['docs']['resources']['subnets']['methods']
466
467 _subnet_create = next(x for x in _subnet_methods if x['name'] == 'create')
468 _subnet_create_params_subnet = next(x for x in _subnet_create['params'] if x['name'] == 'subnet')
469 _subnet_create_params_subnet['params'].append(_subnet_rex_proxies_parameter)
470
471 _subnet_update = next(x for x in _subnet_methods if x['name'] == 'update')
472 _subnet_update_params_subnet = next(x for x in _subnet_update['params'] if x['name'] == 'subnet')
473 _subnet_update_params_subnet['params'].append(_subnet_rex_proxies_parameter)
474
475 @_check_patch_needed(introduced_version='2.1.0', fixed_version='2.3.0')
476 def _patch_subnet_externalipam_group_api(self):
477 """
478 This is a workaround for the broken subnet apidoc for External IPAM.
479 See https://projects.theforeman.org/issues/30890
480 """
481
482 _subnet_externalipam_group_parameter = {
483 u'validations': [],
484 u'name': u'externalipam_group',
485 u'show': True,
486 u'description': u'\n<p>External IPAM group - only relevant when IPAM is set to external</p>\n',
487 u'required': False,
488 u'allow_nil': True,
489 u'allow_blank': False,
490 u'full_name': u'subnet[externalipam_group]',
491 u'expected_type': u'string',
492 u'metadata': None,
493 u'validator': u'',
494 }
495 _subnet_methods = self.foremanapi.apidoc['docs']['resources']['subnets']['methods']
496
497 _subnet_create = next(x for x in _subnet_methods if x['name'] == 'create')
498 _subnet_create_params_subnet = next(x for x in _subnet_create['params'] if x['name'] == 'subnet')
499 _subnet_create_params_subnet['params'].append(_subnet_externalipam_group_parameter)
500
501 _subnet_update = next(x for x in _subnet_methods if x['name'] == 'update')
502 _subnet_update_params_subnet = next(x for x in _subnet_update['params'] if x['name'] == 'subnet')
503 _subnet_update_params_subnet['params'].append(_subnet_externalipam_group_parameter)
504
505 @_check_patch_needed(plugins=['katello'])
506 def _patch_organization_update_api(self):
507 """
508 This is a workaround for the broken organization update apidoc in Katello.
509 See https://projects.theforeman.org/issues/27538
510 """
511
512 _organization_methods = self.foremanapi.apidoc['docs']['resources']['organizations']['methods']
513
514 _organization_update = next(x for x in _organization_methods if x['name'] == 'update')
515 _organization_update_params_organization = next(x for x in _organization_update['params'] if x['name'] == 'organization')
516 _organization_update_params_organization['required'] = False
517
518 @_check_patch_needed(plugins=['katello'])
519 def _patch_cv_filter_rule_api(self):
520 """
521 This is a workaround for missing params of CV Filter Rule update controller in Katello.
522 See https://projects.theforeman.org/issues/30908
523 """
524
525 _content_view_filter_rule_methods = self.foremanapi.apidoc['docs']['resources']['content_view_filter_rules']['methods']
526
527 _content_view_filter_rule_create = next(x for x in _content_view_filter_rule_methods if x['name'] == 'create')
528 _content_view_filter_rule_update = next(x for x in _content_view_filter_rule_methods if x['name'] == 'update')
529
530 for param_name in ['uuid', 'errata_ids', 'date_type', 'module_stream_ids']:
531 create_param = next((x for x in _content_view_filter_rule_create['params'] if x['name'] == param_name), None)
532 update_param = next((x for x in _content_view_filter_rule_update['params'] if x['name'] == param_name), None)
533 if create_param is not None and update_param is None:
534 _content_view_filter_rule_update['params'].append(create_param)
535
536 @_check_patch_needed(fixed_version='3.5.0', plugins=['katello'])
537 def _patch_ak_product_content_per_page(self):
538 """
539 This is a workaround for the API not exposing the per_page param on the product_content endpoint
540 See https://projects.theforeman.org/issues/35633
541 """
542
543 _per_page_param = {
544 "name": "per_page",
545 "full_name": "per_page",
546 "description": "\n<p>Number of results per page to return</p>\n",
547 "required": False,
548 "allow_nil": False,
549 "allow_blank": False,
550 "validator": "Must be a number.",
551 "expected_type": "numeric",
552 "metadata": None,
553 "show": True,
554 "validations": []
555 }
556
557 _ak_methods = self.foremanapi.apidoc['docs']['resources']['activation_keys']['methods']
558
559 _ak_product_content = next(x for x in _ak_methods if x['name'] == 'product_content')
560
561 if next((x for x in _ak_product_content['params'] if x['name'] == 'per_page'), None) is None:
562 _ak_product_content['params'].append(_per_page_param)
563
564 @_check_patch_needed(fixed_version='3.5.0', plugins=['katello'])
565 def _patch_organization_ignore_types_api(self):
566 """
567 This is a workaround for the missing ignore_types in the organization apidoc in Katello.
568 See https://projects.theforeman.org/issues/35687
569 """
570
571 _ignore_types_param = {
572 "name": "ignore_types",
573 "full_name": "organization[ignore_types]",
574 "description": "\n<p>List of resources types that will be automatically associated</p>\n",
575 "required": False,
576 "allow_nil": True,
577 "allow_blank": False,
578 "validator": "Must be an array of any type",
579 "expected_type": "array",
580 "metadata": None,
581 "show": True,
582 "validations": []
583 }
584
585 _organization_methods = self.foremanapi.apidoc['docs']['resources']['organizations']['methods']
586
587 _organization_create = next(x for x in _organization_methods if x['name'] == 'create')
588 _organization_update = next(x for x in _organization_methods if x['name'] == 'update')
589 if next((x for x in _organization_create['params'] if x['name'] == 'ignore_types'), None) is None:
590 _organization_create['params'].append(_ignore_types_param)
591 _organization_update['params'].append(_ignore_types_param)
592
593 @_check_patch_needed(fixed_version='3.8.0', plugins=['katello'])
594 def _patch_products_repositories_allow_nil_credential(self):
595 """
596 This is a workaround for the missing allow_nil: true in the Products and Repositories controllers
597 See https://projects.theforeman.org/issues/36497
598 """
599
600 for resource in ['products', 'repositories']:
601 methods = self.foremanapi.apidoc['docs']['resources'][resource]['methods']
602 for action in ['create', 'update']:
603 resource_action = next(x for x in methods if x['name'] == action)
604 for param in ['gpg_key_id', 'ssl_ca_cert_id', 'ssl_client_cert_id', 'ssl_client_key_id']:
605 resource_param = next(x for x in resource_action['params'] if x['name'] == param)
606 resource_param['allow_nil'] = True
607
608 def check_requirements(self):
609 if not HAS_APYPIE:
610 self.fail_json(msg=missing_required_lib("requests"), exception=APYPIE_IMP_ERR)
611
612 @_exception2fail_json(msg="Failed to connect to Foreman server: {0}")
613 def connect(self):
614 """
615 Connect to the Foreman API.
616
617 This will create a new ``apypie.Api`` instance using the provided server information,
618 check that the API is actually reachable (by calling :func:`status`),
619 apply any required patches to the apidoc and ensure the server has all the plugins installed
620 that are required by the module.
621 """
622
623 verify_ssl = self._foremanapi_ca_path if (self._foremanapi_validate_certs and self._foremanapi_ca_path) else self._foremanapi_validate_certs
624 if self._foremanapi_username and self._foremanapi_password:
625 auth = {'username': to_bytes(self._foremanapi_username), 'password': to_bytes(self._foremanapi_password)}
626 elif self._foremanapi_oauth1_consumer_key and self._foremanapi_oauth1_consumer_secret:
627 auth = {'oauth1_consumer_key': to_bytes(self._foremanapi_oauth1_consumer_key),
628 'oauth1_consumer_secret': to_bytes(self._foremanapi_oauth1_consumer_secret)}
629 elif self._foremanapi_use_gssapi:
630 auth = {'kerberos': self._foremanapi_use_gssapi}
631 else:
632 auth = {}
633 self.foremanapi = apypie.ForemanApi(
634 uri=self._foremanapi_server_url,
635 verify_ssl=verify_ssl,
636 **auth,
637 task_timeout=self.task_timeout,
638 )
639
640 _status = self.status()
641 self.foreman_version = LooseVersion(_status.get('version', '0.0.0'))
642 self.apply_apidoc_patches()
643 self.check_required_plugins()
644
645 def apply_apidoc_patches(self):
646 """
647 Apply patches to the local apidoc representation.
648 When adding another patch, consider that the endpoint in question may depend on a plugin to be available.
649 If possible, make the patch only execute on specific server/plugin versions.
650 """
651
652 self._patch_host_update()
653
654 self._patch_subnet_rex_api()
655 self._patch_subnet_externalipam_group_api()
656
657 # Katello
658 self._patch_organization_update_api()
659 self._patch_cv_filter_rule_api()
660 self._patch_ak_product_content_per_page()
661 self._patch_organization_ignore_types_api()
662 self._patch_products_repositories_allow_nil_credential()
663
664 @_exception2fail_json(msg="Failed to connect to Foreman server: {0}")
665 def status(self):
666 """
667 Call the ``status`` API endpoint to ensure the server is reachable.
668
669 :return: The full API response
670 :rtype: dict
671 """
672
673 return self.foremanapi.resource('home').call('status')
674
675 @_exception2fail_json(msg='Failed to show resource: {0}')
676 def show_resource(self, resource, resource_id, params=None):
677 """
678 Execute the ``show`` action on an entity.
679
680 :param resource: Plural name of the api resource to show
681 :type resource: str
682 :param resource_id: The ID of the entity to show
683 :type resource_id: int
684 :param params: Lookup parameters (i.e. parent_id for nested entities)
685 :type params: Union[dict,None], optional
686 """
687
688 return self.foremanapi.show(resource, resource_id, params)
689
690 @_exception2fail_json(msg='Failed to list resource: {0}')
691 def list_resource(self, resource, search=None, params=None):
692 """
693 Execute the ``index`` action on an resource.
694
695 :param resource: Plural name of the api resource to show
696 :type resource: str
697 :param search: Search string as accepted by the API to limit the results
698 :type search: str, optional
699 :param params: Lookup parameters (i.e. parent_id for nested entities)
700 :type params: Union[dict,None], optional
701 """
702
703 return self.foremanapi.list(resource, search, params)
704
705 def find_resource(self, resource, search, params=None, failsafe=False, thin=None):
706 list_params = {}
707 if params is not None:
708 list_params.update(params)
709 if thin is None:
710 thin = self._thin_default
711 list_params['thin'] = thin
712 results = self.list_resource(resource, search, list_params)
713 if len(results) == 1:
714 result = results[0]
715 elif failsafe:
716 result = None
717 else:
718 if len(results) > 1:
719 error_msg = "too many ({0})".format(len(results))
720 else:
721 error_msg = "no"
722 self.fail_json(msg="Found {0} results while searching for {1} with {2}".format(error_msg, resource, search))
723 if result and not thin:
724 result = self.show_resource(resource, result['id'], params=params)
725 return result
726
727 def find_resource_by(self, resource, search_field, value, **kwargs):
728 if not value:
729 return NoEntity
730 search = '{0}{1}"{2}"'.format(search_field, kwargs.pop('search_operator', '='), value)
731 return self.find_resource(resource, search, **kwargs)
732
733 def find_resource_by_name(self, resource, name, **kwargs):
734 return self.find_resource_by(resource, 'name', name, **kwargs)
735
736 def find_resource_by_title(self, resource, title, **kwargs):
737 return self.find_resource_by(resource, 'title', title, **kwargs)
738
739 def find_resource_by_id(self, resource, obj_id, **kwargs):
740 return self.find_resource_by(resource, 'id', obj_id, **kwargs)
741
742 def find_resources_by_name(self, resource, names, **kwargs):
743 return [self.find_resource_by_name(resource, name, **kwargs) for name in names]
744
745 def find_operatingsystem(self, name, failsafe=False, **kwargs):
746 result = self.find_resource_by_title('operatingsystems', name, failsafe=True, **kwargs)
747 if not result:
748 result = self.find_resource_by('operatingsystems', 'title', name, search_operator='~', failsafe=failsafe, **kwargs)
749 return result
750
751 def find_puppetclass(self, name, environment=None, params=None, failsafe=False, thin=None):
752 if thin is None:
753 thin = self._thin_default
754 if environment:
755 scope = {'environment_id': environment}
756 else:
757 scope = {}
758 if params is not None:
759 scope.update(params)
760 search = 'name="{0}"'.format(name)
761 results = self.list_resource('puppetclasses', search, params=scope)
762
763 # verify that only one puppet module is returned with only one puppet class inside
764 # as provided search results have to be like "results": { "ntp": [{"id": 1, "name": "ntp" ...}]}
765 # and get the puppet class id
766 if len(results) == 1 and len(list(results.values())[0]) == 1:
767 result = list(results.values())[0][0]
768 if thin:
769 return {'id': result['id']}
770 else:
771 return result
772
773 if failsafe:
774 return None
775 else:
776 self.fail_json(msg='No data found for name="%s"' % search)
777
778 def find_puppetclasses(self, names, **kwargs):
779 return [self.find_puppetclass(name, **kwargs) for name in names]
780
781 def find_cluster(self, name, compute_resource):
782 cluster = self.find_compute_resource_parts('clusters', name, compute_resource, None, ['ovirt', 'vmware'])
783
784 # workaround for https://projects.theforeman.org/issues/31874
785 if compute_resource['provider'].lower() == 'vmware':
786 path_or_name = cluster.get('full_path', cluster['name'])
787 cluster['_api_identifier'] = path_or_name
788 else:
789 cluster['_api_identifier'] = cluster['id']
790
791 return cluster
792
793 def find_network(self, name, compute_resource, cluster=None):
794 return self.find_compute_resource_parts('networks', name, compute_resource, cluster, ['ovirt', 'vmware', 'google', 'azurerm'])
795
796 def find_storage_domain(self, name, compute_resource, cluster=None):
797 return self.find_compute_resource_parts('storage_domains', name, compute_resource, cluster, ['ovirt', 'vmware'])
798
799 def find_storage_pod(self, name, compute_resource, cluster=None):
800 return self.find_compute_resource_parts('storage_pods', name, compute_resource, cluster, ['vmware'])
801
802 def find_compute_resource_parts(self, part_name, name, compute_resource, cluster=None, supported_crs=None):
803 if supported_crs is None:
804 supported_crs = []
805
806 if compute_resource['provider'].lower() not in supported_crs:
807 return {'id': name, 'name': name}
808
809 additional_params = {'id': compute_resource['id']}
810 if cluster is not None:
811 # apypie will quote the params for us, but we need to do it twice for the cluster_id
812 # see https://projects.theforeman.org/issues/35438
813 # and https://github.com/theforeman/hammer-cli-foreman/pull/604
814 # and https://github.com/theforeman/foreman/pull/9383
815 # and https://httpd.apache.org/docs/current/mod/core.html#allowencodedslashes
816 additional_params['cluster_id'] = six.moves.urllib.parse.quote(cluster['_api_identifier'], safe='')
817 api_name = 'available_{0}'.format(part_name)
818 available_parts = self.resource_action('compute_resources', api_name, params=additional_params,
819 ignore_check_mode=True, record_change=False)['results']
820 part = next((part for part in available_parts
821 if str(part['name']) == str(name) or str(part['id']) == str(name) or part.get('full_path') == str(name)),
822 None)
823 if part is None:
824 err_msg = "Could not find {0} '{1}' on compute resource '{2}'.".format(part_name, name, compute_resource.get('name'))
825 self.fail_json(msg=err_msg)
826 return part
827
828 def scope_for(self, key, scoped_resource=None):
829 # workaround for https://projects.theforeman.org/issues/31714
830 if scoped_resource in ['content_views', 'repositories'] and key == 'lifecycle_environment':
831 scope_key = 'environment'
832 else:
833 scope_key = key
834 return {'{0}_id'.format(scope_key): self.lookup_entity(key)['id']}
835
836 def set_entity(self, key, entity):
837 self.foreman_params[key] = entity
838
839 def lookup_entity(self, key, params=None):
840 if key not in self.foreman_params:
841 return None
842
843 entity_spec = self.foreman_spec[key]
844 if _is_resolved(entity_spec, self.foreman_params[key]):
845 # Already looked up or not an entity(_list) so nothing to do
846 return self.foreman_params[key]
847
848 result = self._lookup_entity(self.foreman_params[key], entity_spec, params)
849 self.set_entity(key, result)
850 return result
851
852 def _lookup_entity(self, identifier, entity_spec, params=None):
853 if identifier is NoEntity:
854 return NoEntity
855 resource_type = entity_spec['resource_type']
856 failsafe = entity_spec.get('failsafe', False)
857 thin = entity_spec.get('thin', True)
858 if params:
859 params = params.copy()
860 else:
861 params = {}
862 try:
863 for scope in entity_spec.get('scope', []):
864 params.update(self.scope_for(scope, resource_type))
865 for optional_scope in entity_spec.get('optional_scope', []):
866 if optional_scope in self.foreman_params:
867 params.update(self.scope_for(optional_scope, resource_type))
868
869 except TypeError:
870 if failsafe:
871 if entity_spec.get('type') == 'entity':
872 result = None
873 else:
874 result = [None for value in identifier]
875 else:
876 self.fail_json(msg="Failed to lookup scope {0} while searching for {1}.".format(entity_spec['scope'], resource_type))
877 else:
878 # No exception happend => scope is in place
879 if resource_type == 'operatingsystems':
880 if entity_spec.get('type') == 'entity':
881 result = self.find_operatingsystem(identifier, params=params, failsafe=failsafe, thin=thin)
882 else:
883 result = [self.find_operatingsystem(value, params=params, failsafe=failsafe, thin=thin) for value in identifier]
884 elif resource_type == 'puppetclasses':
885 if entity_spec.get('type') == 'entity':
886 result = self.find_puppetclass(identifier, params=params, failsafe=failsafe, thin=thin)
887 else:
888 result = [self.find_puppetclass(value, params=params, failsafe=failsafe, thin=thin) for value in identifier]
889 else:
890 if entity_spec.get('type') == 'entity':
891 result = self.find_resource_by(
892 resource=resource_type,
893 value=identifier,
894 search_field=entity_spec.get('search_by', ENTITY_KEYS.get(resource_type, 'name')),
895 search_operator=entity_spec.get('search_operator', '='),
896 failsafe=failsafe, thin=thin, params=params,
897 )
898 else:
899 result = [self.find_resource_by(
900 resource=resource_type,
901 value=value,
902 search_field=entity_spec.get('search_by', ENTITY_KEYS.get(resource_type, 'name')),
903 search_operator=entity_spec.get('search_operator', '='),
904 failsafe=failsafe, thin=thin, params=params,
905 ) for value in identifier]
906 return result
907
908 def auto_lookup_entities(self):
909 self.auto_lookup_nested_entities()
910 return [
911 self.lookup_entity(key)
912 for key, entity_spec in self.foreman_spec.items()
913 if entity_spec.get('resolve', True) and entity_spec.get('type') in {'entity', 'entity_list'}
914 ]
915
916 def auto_lookup_nested_entities(self):
917 for key, entity_spec in self.foreman_spec.items():
918 if entity_spec.get('type') in {'nested_list'}:
919 for nested_key, nested_spec in entity_spec['foreman_spec'].items():
920 for item in self.foreman_params.get(key, []):
921 if (nested_key in item and nested_spec.get('resolve', True)
922 and not _is_resolved(nested_spec, item[nested_key])):
923 item[nested_key] = self._lookup_entity(item[nested_key], nested_spec)
924
925 def record_before(self, resource, entity):
926 if isinstance(entity, dict):
927 to_record = _recursive_dict_without_none(entity)
928 else:
929 to_record = entity
930 self._before[resource].append(to_record)
931
932 def record_after(self, resource, entity):
933 if isinstance(entity, dict):
934 to_record = _recursive_dict_without_none(entity)
935 else:
936 to_record = entity
937 self._after[resource].append(to_record)
938
939 def record_after_full(self, resource, entity):
940 self._after_full[resource].append(entity)
941
942 @_exception2fail_json(msg='Failed to ensure entity state: {0}')
943 def ensure_entity(self, resource, desired_entity, current_entity, params=None, state=None, foreman_spec=None):
944 """
945 Ensure that a given entity has a certain state
946
947 :param resource: Plural name of the api resource to manipulate
948 :type resource: str
949 :param desired_entity: Desired properties of the entity
950 :type desired_entity: dict
951 :param current_entity: Current properties of the entity or None if nonexistent
952 :type current_entity: Union[dict,None]
953 :param params: Lookup parameters (i.e. parent_id for nested entities)
954 :type params: dict, optional
955 :param state: Desired state of the entity (optionally taken from the module)
956 :type state: str, optional
957 :param foreman_spec: Description of the entity structure (optionally taken from module)
958 :type foreman_spec: dict, optional
959
960 :return: The new current state of the entity
961 :rtype: Union[dict,None]
962 """
963 if state is None:
964 state = self.state
965 if foreman_spec is None:
966 foreman_spec = self.foreman_spec
967 else:
968 foreman_spec, _dummy = _foreman_spec_helper(foreman_spec)
969
970 updated_entity = None
971
972 self.record_before(resource, _flatten_entity(current_entity, foreman_spec))
973
974 if state == 'present_with_defaults':
975 if current_entity is None:
976 updated_entity = self._create_entity(resource, desired_entity, params, foreman_spec)
977 elif state == 'present':
978 if current_entity is None:
979 updated_entity = self._create_entity(resource, desired_entity, params, foreman_spec)
980 else:
981 updated_entity = self._update_entity(resource, desired_entity, current_entity, params, foreman_spec)
982 elif state == 'copied':
983 if current_entity is not None:
984 updated_entity = self._copy_entity(resource, desired_entity, current_entity, params)
985 elif state == 'reverted':
986 if current_entity is not None:
987 updated_entity = self._revert_entity(resource, current_entity, params)
988 elif state == 'new_snapshot':
989 updated_entity = self._create_entity(resource, desired_entity, params, foreman_spec)
990 elif state == 'absent':
991 if current_entity is not None:
992 updated_entity = self._delete_entity(resource, current_entity, params)
993 else:
994 self.fail_json(msg='Not a valid state: {0}'.format(state))
995
996 self.record_after(resource, _flatten_entity(updated_entity, foreman_spec))
997 self.record_after_full(resource, updated_entity)
998
999 return updated_entity
1000
1001 def _validate_supported_payload(self, resource, action, payload):
1002 """
1003 Check whether the payload only contains supported keys.
1004 Emits a warning for keys that are not part of the apidoc.
1005
1006 :param resource: Plural name of the api resource to check
1007 :type resource: str
1008 :param action: Name of the action to check payload against
1009 :type action: str
1010 :param payload: API paylod to be checked
1011 :type payload: dict
1012
1013 :return: The payload as it can be submitted to the API
1014 :rtype: dict
1015 """
1016 filtered_payload, unsupported_parameters = self.foremanapi.validate_payload(resource, action, payload)
1017 if unsupported_parameters:
1018 warn_msg = "The following parameters are not supported by your server when performing {0} on {1}: {2}. They were ignored."
1019 self.warn(warn_msg.format(action, resource, unsupported_parameters))
1020 return filtered_payload
1021
1022 def _create_entity(self, resource, desired_entity, params, foreman_spec):
1023 """
1024 Create entity with given properties
1025
1026 :param resource: Plural name of the api resource to manipulate
1027 :type resource: str
1028 :param desired_entity: Desired properties of the entity
1029 :type desired_entity: dict
1030 :param params: Lookup parameters (i.e. parent_id for nested entities)
1031 :type params: dict, optional
1032 :param foreman_spec: Description of the entity structure
1033 :type foreman_spec: dict
1034
1035 :return: The new current state of the entity
1036 :rtype: dict
1037 """
1038 payload = _flatten_entity(desired_entity, foreman_spec)
1039 self._validate_supported_payload(resource, 'create', payload)
1040 self.set_changed()
1041 if not self.check_mode:
1042 return self.foremanapi.create(resource, payload, params)
1043 else:
1044 fake_entity = desired_entity.copy()
1045 fake_entity['id'] = -1
1046 return fake_entity
1047
1048 def _update_entity(self, resource, desired_entity, current_entity, params, foreman_spec):
1049 """
1050 Update a given entity with given properties if any diverge
1051
1052 :param resource: Plural name of the api resource to manipulate
1053 :type resource: str
1054 :param desired_entity: Desired properties of the entity
1055 :type desired_entity: dict
1056 :param current_entity: Current properties of the entity
1057 :type current_entity: dict
1058 :param params: Lookup parameters (i.e. parent_id for nested entities)
1059 :type params: dict, optional
1060 :param foreman_spec: Description of the entity structure
1061 :type foreman_spec: dict
1062
1063 :return: The new current state of the entity
1064 :rtype: dict
1065 """
1066 payload = {}
1067 desired_entity = _flatten_entity(desired_entity, foreman_spec)
1068 current_flat_entity = _flatten_entity(current_entity, foreman_spec)
1069 for key, value in desired_entity.items():
1070 foreman_type = foreman_spec[key].get('type', 'str')
1071 new_value = value
1072 old_value = current_flat_entity.get(key)
1073 # String comparison needs extra care in face of unicode
1074 if foreman_type == 'str':
1075 old_value = to_native(old_value)
1076 new_value = to_native(new_value)
1077 # ideally the type check would happen via foreman_spec.elements
1078 # however this is not set for flattened entries and setting it
1079 # confuses _flatten_entity
1080 elif foreman_type == 'list' and value and isinstance(value[0], dict):
1081 # special handling for parameters created by ParametersMixin
1082 # they are defined as a list of dict, but the dicts should be really handled like
1083 # entities, which means we only want to update the user-provided details
1084 if key.endswith('_parameters_attributes'):
1085 for new_param in new_value:
1086 old_param = next((x for x in old_value if x['name'] == new_param['name']), None)
1087 if old_param is not None:
1088 for pop_key in set(old_param.keys()) - set(new_param.keys()):
1089 old_param.pop(pop_key)
1090 if 'name' in value[0]:
1091 sort_key = 'name'
1092 else:
1093 sort_key = list(value[0].keys())[0]
1094 new_value = sorted(new_value, key=operator.itemgetter(sort_key))
1095 old_value = sorted(old_value, key=operator.itemgetter(sort_key))
1096 if new_value != old_value:
1097 payload[key] = value
1098 # workaround to ensure LCE and CV are always sent together, even if only one changed
1099 # using the values from the existing entity, so the user doesn't need to pass it in their playbook
1100 if resource == 'hosts':
1101 if 'content_view_id' in payload and 'lifecycle_environment_id' not in payload:
1102 payload['lifecycle_environment_id'] = current_flat_entity['lifecycle_environment_id']
1103 elif 'lifecycle_environment_id' in payload and 'content_view_id' not in payload:
1104 payload['content_view_id'] = current_flat_entity['content_view_id']
1105 elif resource == 'activation_keys':
1106 if 'content_view_id' in payload and 'environment_id' not in payload:
1107 payload['environment_id'] = current_flat_entity['environment_id']
1108 elif 'environment_id' in payload and 'content_view_id' not in payload:
1109 payload['content_view_id'] = current_flat_entity['content_view_id']
1110 if self._validate_supported_payload(resource, 'update', payload):
1111 self.set_changed()
1112 payload['id'] = current_flat_entity['id']
1113 if not self.check_mode:
1114 return self.foremanapi.update(resource, payload, params)
1115 else:
1116 # In check_mode we emulate the server updating the entity
1117 fake_entity = current_flat_entity.copy()
1118 fake_entity.update(payload)
1119 return fake_entity
1120 else:
1121 # Nothing needs changing
1122 return current_entity
1123
1124 def _copy_entity(self, resource, desired_entity, current_entity, params):
1125 """
1126 Copy a given entity
1127
1128 :param resource: Plural name of the api resource to manipulate
1129 :type resource: str
1130 :param desired_entity: Desired properties of the entity
1131 :type desired_entity: dict
1132 :param current_entity: Current properties of the entity
1133 :type current_entity: dict
1134 :param params: Lookup parameters (i.e. parent_id for nested entities)
1135 :type params: dict, optional
1136
1137 :return: The new current state of the entity
1138 :rtype: dict
1139 """
1140 payload = {
1141 'id': current_entity['id'],
1142 'new_name': desired_entity['new_name'],
1143 }
1144 if params:
1145 payload.update(params)
1146 return self.resource_action(resource, 'copy', payload)
1147
1148 def _revert_entity(self, resource, current_entity, params):
1149 """
1150 Revert a given entity
1151
1152 :param resource: Plural name of the api resource to manipulate
1153 :type resource: str
1154 :param current_entity: Current properties of the entity
1155 :type current_entity: dict
1156 :param params: Lookup parameters (i.e. parent_id for nested entities)
1157 :type params: dict, optional
1158
1159 :return: The new current state of the entity
1160 :rtype: dict
1161 """
1162 payload = {'id': current_entity['id']}
1163 if params:
1164 payload.update(params)
1165 return self.resource_action(resource, 'revert', payload)
1166
1167 def _delete_entity(self, resource, current_entity, params):
1168 """
1169 Delete a given entity
1170
1171 :param resource: Plural name of the api resource to manipulate
1172 :type resource: str
1173 :param current_entity: Current properties of the entity
1174 :type current_entity: dict
1175 :param params: Lookup parameters (i.e. parent_id for nested entities)
1176 :type params: dict, optional
1177
1178 :return: The new current state of the entity
1179 :rtype: Union[dict,None]
1180 """
1181 self.set_changed()
1182 if not self.check_mode:
1183 return self.foremanapi.delete(resource, current_entity, params)
1184 else:
1185 return None
1186
1187 def resource_action(self, resource, action, params, options=None, data=None, files=None,
1188 ignore_check_mode=False, record_change=True, ignore_task_errors=False):
1189 try:
1190 result = None
1191 if ignore_check_mode or not self.check_mode:
1192 result = self.foremanapi.resource_action(resource, action, params, options, data, files, ignore_task_errors)
1193 except Exception as e:
1194 msg = 'Error while performing {0} on {1}: {2}'.format(
1195 action, resource, to_native(e))
1196 self.fail_from_exception(e, msg)
1197 if record_change and not ignore_check_mode:
1198 # If we were supposed to ignore check_mode we can assume this action was not a changing one.
1199 self.set_changed()
1200 return result
1201
1202 def wait_for_task(self, task, ignore_errors=False):
1203 return self.foremanapi.wait_for_task(task, ignore_errors)
1204
1205 def fail_from_exception(self, exc, msg):
1206 fail = {'msg': msg}
1207 if isinstance(exc, requests.exceptions.HTTPError):
1208 try:
1209 response = exc.response.json()
1210 if 'error' in response:
1211 fail['error'] = response['error']
1212 else:
1213 fail['error'] = response
1214 except Exception:
1215 fail['error'] = exc.response.text
1216 self.fail_json(**fail)
1217
1218 def exit_json(self, changed=False, **kwargs):
1219 kwargs['changed'] = changed or self.changed
1220 if 'diff' not in kwargs and (self._before or self._after):
1221 kwargs['diff'] = {'before': self._before,
1222 'after': self._after}
1223 if 'entity' not in kwargs and self._after_full:
1224 kwargs['entity'] = self._after_full
1225 super(ForemanAnsibleModule, self).exit_json(**kwargs)
1226
1227 def has_plugin(self, plugin_name):
1228 try:
1229 resource_name = _PLUGIN_RESOURCES[plugin_name]
1230 except KeyError:
1231 raise Exception("Unknown plugin: {0}".format(plugin_name))
1232 return resource_name in self.foremanapi.resources
1233
1234 def check_required_plugins(self):
1235 missing_plugins = []
1236 for (plugin, params) in self.required_plugins:
1237 for param in params:
1238 if (param in self.foreman_params or param == '*') and not self.has_plugin(plugin):
1239 if param == '*':
1240 param = 'the whole module'
1241 missing_plugins.append("{0} (for {1})".format(plugin, param))
1242 if missing_plugins:
1243 missing_msg = "The server is missing required plugins: {0}.".format(', '.join(missing_plugins))
1244 self.fail_json(msg=missing_msg)
1245
1246
1247 class ForemanStatelessEntityAnsibleModule(ForemanAnsibleModule):
1248 """ Base class for Foreman entities without a state. To use it, subclass it with the following convention:
1249 To manage my_entity entity, create the following sub class::
1250
1251 class ForemanMyEntityModule(ForemanStatelessEntityAnsibleModule):
1252 pass
1253
1254 and use that class to instantiate module::
1255
1256 module = ForemanMyEntityModule(
1257 argument_spec=dict(
1258 [...]
1259 ),
1260 foreman_spec=dict(
1261 [...]
1262 ),
1263 )
1264
1265 It adds the following attributes:
1266
1267 * entity_key (str): field used to search current entity. Defaults to value provided by `ENTITY_KEYS` or 'name' if no value found.
1268 * entity_name (str): name of the current entity.
1269 By default deduce the entity name from the class name (eg: 'ForemanProvisioningTemplateModule' class will produce 'provisioning_template').
1270 * entity_opts (dict): Dict of options for base entity. Same options can be provided for subentities described in foreman_spec.
1271
1272 The main entity is referenced with the key `entity` in the `foreman_spec`.
1273 """
1274
1275 def __init__(self, **kwargs):
1276 self.entity_key = kwargs.pop('entity_key', 'name')
1277 self.entity_name = kwargs.pop('entity_name', self.entity_name_from_class)
1278 entity_opts = kwargs.pop('entity_opts', {})
1279
1280 super(ForemanStatelessEntityAnsibleModule, self).__init__(**kwargs)
1281
1282 if 'resource_type' not in entity_opts:
1283 entity_opts['resource_type'] = inflector.pluralize(self.entity_name)
1284 if 'thin' not in entity_opts:
1285 # Explicit None to trigger the _thin_default mechanism lazily
1286 entity_opts['thin'] = None
1287 if 'failsafe' not in entity_opts:
1288 entity_opts['failsafe'] = True
1289 if 'search_operator' not in entity_opts:
1290 entity_opts['search_operator'] = '='
1291 if 'search_by' not in entity_opts:
1292 entity_opts['search_by'] = ENTITY_KEYS.get(entity_opts['resource_type'], 'name')
1293
1294 self.foreman_spec.update(_foreman_spec_helper(dict(
1295 entity=dict(
1296 type='entity',
1297 flat_name='id',
1298 ensure=False,
1299 **entity_opts
1300 ),
1301 ))[0])
1302
1303 if 'parent' in self.foreman_spec and self.foreman_spec['parent'].get('type') == 'entity':
1304 # ensure parent and entity are the same type
1305 self.foreman_spec['parent']['resource_type'] = self.foreman_spec['entity']['resource_type']
1306 if 'failsafe' not in self.foreman_spec['parent']:
1307 self.foreman_spec['parent']['failsafe'] = True
1308 current, parent = split_fqn(self.foreman_params[self.entity_key])
1309 if isinstance(self.foreman_params.get('parent'), six.string_types):
1310 if parent:
1311 self.fail_json(msg="Please specify the parent either separately, or as part of the title.")
1312 parent = self.foreman_params['parent']
1313 elif parent:
1314 self.foreman_params['parent'] = parent
1315 self.foreman_params[self.entity_key] = current
1316 self.foreman_params['entity'] = build_fqn(current, parent)
1317 else:
1318 self.foreman_params['entity'] = self.foreman_params.get(self.entity_key)
1319
1320 @property
1321 def entity_name_from_class(self):
1322 """
1323 The entity name derived from the class name.
1324
1325 The class name must follow the following name convention:
1326
1327 * It starts with ``Foreman`` or ``Katello``.
1328 * It ends with ``Module``.
1329
1330 This will convert the class name ``ForemanMyEntityModule`` to the entity name ``my_entity``.
1331
1332 Examples:
1333
1334 * ``ForemanArchitectureModule`` => ``architecture``
1335 * ``ForemanProvisioningTemplateModule`` => ``provisioning_template``
1336 * ``KatelloProductMudule`` => ``product``
1337 """
1338 # Convert current class name from CamelCase to snake_case
1339 class_name = re.sub(r'(?<=[a-z])[A-Z]|[A-Z](?=[^A-Z])', r'_\g<0>', self.__class__.__name__).lower().strip('_')
1340 # Get entity name from snake case class name
1341 return '_'.join(class_name.split('_')[1:-1])
1342
1343
1344 class ForemanInfoAnsibleModule(ForemanStatelessEntityAnsibleModule):
1345 """
1346 Base class for Foreman info modules that fetch information about entities
1347 """
1348 def __init__(self, **kwargs):
1349 self._resources = []
1350 foreman_spec = dict(
1351 name=dict(),
1352 search=dict(),
1353 organization=dict(type='entity'),
1354 location=dict(type='entity'),
1355 )
1356 foreman_spec.update(kwargs.pop('foreman_spec', {}))
1357 mutually_exclusive = kwargs.pop('mutually_exclusive', [])
1358 if not foreman_spec['name'].get('invisible', False):
1359 mutually_exclusive.extend([['name', 'search']])
1360 super(ForemanInfoAnsibleModule, self).__init__(foreman_spec=foreman_spec, mutually_exclusive=mutually_exclusive, **kwargs)
1361
1362 def run(self, **kwargs):
1363 """
1364 lookup entities
1365 """
1366 self.auto_lookup_entities()
1367
1368 resource = self.foreman_spec['entity']['resource_type']
1369
1370 if 'name' in self.foreman_params:
1371 self._info_result = {self.entity_name: self.lookup_entity('entity')}
1372 else:
1373 _flat_entity = _flatten_entity(self.foreman_params, self.foreman_spec)
1374 self._info_result = {resource: self.list_resource(resource, self.foreman_params.get('search'), _flat_entity)}
1375
1376 def exit_json(self, **kwargs):
1377 kwargs.update(self._info_result)
1378 super(ForemanInfoAnsibleModule, self).exit_json(**kwargs)
1379
1380
1381 class ForemanEntityAnsibleModule(ForemanStatelessEntityAnsibleModule):
1382 """ Base class for Foreman entities. To use it, subclass it with the following convention:
1383 To manage my_entity entity, create the following sub class::
1384
1385 class ForemanMyEntityModule(ForemanEntityAnsibleModule):
1386 pass
1387
1388 and use that class to instantiate module::
1389
1390 module = ForemanMyEntityModule(
1391 argument_spec=dict(
1392 [...]
1393 ),
1394 foreman_spec=dict(
1395 [...]
1396 ),
1397 )
1398
1399 This adds a `state` parameter to the module and provides the `run` method for the most
1400 common usecases.
1401 """
1402
1403 def __init__(self, **kwargs):
1404 argument_spec = dict(
1405 state=dict(choices=['present', 'absent'], default='present'),
1406 )
1407 argument_spec.update(kwargs.pop('argument_spec', {}))
1408 super(ForemanEntityAnsibleModule, self).__init__(argument_spec=argument_spec, **kwargs)
1409
1410 self.state = self.foreman_params.pop('state')
1411 self.desired_absent = self.state == 'absent'
1412 self._thin_default = self.desired_absent
1413
1414 def run(self, **kwargs):
1415 """ lookup entities, ensure entity, remove sensitive data, manage parameters.
1416 """
1417 parent_name = self.foreman_params.get('parent')
1418 if ('parent' in self.foreman_spec and self.foreman_spec['parent'].get('type') == 'entity'
1419 and 'parent' in self.foreman_params and self.lookup_entity('parent') is None):
1420 if self.desired_absent:
1421 # Parent does not exist so just exit here
1422 return None
1423 else:
1424 self.fail_json(msg="Couldn't find parent '{0}' for '{1}'.".format(parent_name, self.foreman_params['name']))
1425 if not self.desired_absent:
1426 self.auto_lookup_entities()
1427 entity = self.lookup_entity('entity')
1428
1429 if not self.desired_absent:
1430 updated_key = "updated_" + self.entity_key
1431 if entity and updated_key in self.foreman_params:
1432 self.foreman_params[self.entity_key] = self.foreman_params.pop(updated_key)
1433
1434 params = kwargs.get('params', {})
1435 for scope in self.foreman_spec['entity'].get('scope', []):
1436 params.update(self.scope_for(scope))
1437 for optional_scope in self.foreman_spec['entity'].get('optional_scope', []):
1438 if optional_scope in self.foreman_params:
1439 params.update(self.scope_for(optional_scope))
1440 new_entity = self.ensure_entity(self.foreman_spec['entity']['resource_type'], self.foreman_params, entity, params=params)
1441 new_entity = self.remove_sensitive_fields(new_entity)
1442
1443 return new_entity
1444
1445 def remove_sensitive_fields(self, entity):
1446 """ Set fields with 'no_log' option to None """
1447 if entity:
1448 for blacklisted_field in self.blacklisted_fields:
1449 entity[blacklisted_field] = None
1450 return entity
1451
1452 @property
1453 def blacklisted_fields(self):
1454 return [key for key, value in self.foreman_spec.items() if value.get('no_log', False)]
1455
1456
1457 class ForemanTaxonomicAnsibleModule(TaxonomyMixin, ForemanAnsibleModule):
1458 """
1459 Combine :class:`ForemanAnsibleModule` with the :class:`TaxonomyMixin` Mixin.
1460 """
1461
1462 pass
1463
1464
1465 class ForemanTaxonomicEntityAnsibleModule(TaxonomyMixin, ForemanEntityAnsibleModule):
1466 """
1467 Combine :class:`ForemanEntityAnsibleModule` with the :class:`TaxonomyMixin` Mixin.
1468 """
1469
1470 pass
1471
1472
1473 class ForemanScapDataStreamModule(ForemanTaxonomicEntityAnsibleModule):
1474 def __init__(self, **kwargs):
1475 foreman_spec = dict(
1476 original_filename=dict(type='str'),
1477 scap_file=dict(type='path'),
1478 )
1479 foreman_spec.update(kwargs.pop('foreman_spec', {}))
1480 super(ForemanScapDataStreamModule, self).__init__(foreman_spec=foreman_spec, **kwargs)
1481
1482 def run(self, **kwargs):
1483 entity = self.lookup_entity('entity')
1484
1485 if not self.desired_absent:
1486 if not entity and 'scap_file' not in self.foreman_params:
1487 self.fail_json(msg="Content of scap_file not provided. XML containing SCAP content is required.")
1488
1489 if 'scap_file' in self.foreman_params and 'original_filename' not in self.foreman_params:
1490 self.foreman_params['original_filename'] = os.path.basename(self.foreman_params['scap_file'])
1491
1492 if 'scap_file' in self.foreman_params:
1493 with open(self.foreman_params['scap_file']) as input_file:
1494 self.foreman_params['scap_file'] = input_file.read()
1495
1496 if entity and 'scap_file' in self.foreman_params:
1497 digest = hashlib.sha256(self.foreman_params['scap_file'].encode("utf-8")).hexdigest()
1498 # workaround for https://projects.theforeman.org/issues/29409
1499 digest_stripped = hashlib.sha256(self.foreman_params['scap_file'].strip().encode("utf-8")).hexdigest()
1500 if entity['digest'] in [digest, digest_stripped]:
1501 self.foreman_params.pop('scap_file')
1502
1503 return super(ForemanScapDataStreamModule, self).run(**kwargs)
1504
1505
1506 class KatelloAnsibleModule(KatelloMixin, ForemanAnsibleModule):
1507 """
1508 Combine :class:`ForemanAnsibleModule` with the :class:`KatelloMixin` Mixin.
1509 """
1510
1511 pass
1512
1513
1514 class KatelloScopedMixin(KatelloMixin):
1515 """
1516 Enhances :class:`KatelloMixin` with scoping by ``organization`` as required by Katello.
1517 """
1518
1519 def __init__(self, **kwargs):
1520 entity_opts = kwargs.pop('entity_opts', {})
1521 if 'scope' not in entity_opts:
1522 entity_opts['scope'] = ['organization']
1523 elif 'organization' not in entity_opts['scope']:
1524 entity_opts['scope'].append('organization')
1525 super(KatelloScopedMixin, self).__init__(entity_opts=entity_opts, **kwargs)
1526
1527
1528 class KatelloInfoAnsibleModule(KatelloScopedMixin, ForemanInfoAnsibleModule):
1529 """
1530 Combine :class:`ForemanInfoAnsibleModule` with the :class:`KatelloScopedMixin` Mixin.
1531 """
1532
1533 pass
1534
1535
1536 class KatelloEntityAnsibleModule(KatelloScopedMixin, ForemanEntityAnsibleModule):
1537 """
1538 Combine :class:`ForemanEntityAnsibleModule` with the :class:`KatelloScopedMixin` Mixin.
1539 """
1540
1541 pass
1542
1543
1544 class KatelloContentExportBaseModule(KatelloAnsibleModule):
1545
1546 def __init__(self, **kwargs):
1547 foreman_spec = dict(
1548 chunk_size_gb=dict(required=False, type='int'),
1549 format=dict(required=False, type='str', choices=['syncable', 'importable']),
1550 from_history_id=dict(required=False, type='int'),
1551 )
1552 argument_spec = dict(
1553 incremental=dict(required=False, type='bool'),
1554 )
1555
1556 foreman_spec.update(kwargs.pop('foreman_spec', {}))
1557 argument_spec.update(kwargs.pop('argument_spec', {}))
1558
1559 self.export_action = kwargs.pop('export_action')
1560
1561 super(KatelloContentExportBaseModule, self).__init__(foreman_spec=foreman_spec, argument_spec=argument_spec, **kwargs)
1562
1563 # needs to happen after super().__init__()
1564 self.task_timeout = 12 * 60 * 60
1565
1566 def run(self, **kwargs):
1567 incremental = self.params['incremental']
1568 endpoint = 'content_export_incrementals' if incremental else 'content_exports'
1569
1570 if self.params.get('from_history_id') and incremental is not True:
1571 self.fail_json(msg='from_history_id is only valid for incremental exports')
1572
1573 if 'chunk_size_gb' in self.foreman_params and self.foreman_params['format'] == 'syncable':
1574 self.fail_json(msg='chunk_size_gb is only valid for importable exports')
1575
1576 self.auto_lookup_entities()
1577
1578 payload = _flatten_entity(self.foreman_params, self.foreman_spec)
1579 task = self.resource_action(endpoint, self.export_action, payload)
1580
1581 self.exit_json(task=task)
1582
1583
1584 class KatelloContentImportBaseModule(KatelloAnsibleModule):
1585
1586 def __init__(self, **kwargs):
1587 foreman_spec = dict(
1588 path=dict(required=True, type='str'),
1589 metadata_file=dict(required=False, type='str'),
1590 metadata=dict(required=False, type='dict')
1591 )
1592 argument_spec = {}
1593 foreman_spec.update(kwargs.pop('foreman_spec', {}))
1594 argument_spec.update(kwargs.pop('argument_spec', {}))
1595
1596 self.import_action = kwargs.pop('import_action')
1597
1598 super(KatelloContentImportBaseModule, self).__init__(foreman_spec=foreman_spec,
1599 required_one_of=[['metadata', 'metadata_file']],
1600 argument_spec=argument_spec, **kwargs)
1601
1602 # needs to happen after super().__init__()
1603 self.task_timeout = 12 * 60 * 60
1604
1605 def run(self, **kwargs):
1606 metadata_file = self.params.get('metadata_file')
1607 self.auto_lookup_entities()
1608 payload = _flatten_entity(self.foreman_params, self.foreman_spec)
1609
1610 if payload.get("metadata") is None and metadata_file:
1611 payload["metadata"] = json.load(open(metadata_file))
1612 payload.pop("metadata_file")
1613
1614 endpoint = 'content_imports'
1615 task = self.resource_action(endpoint, self.import_action, payload)
1616 self.exit_json(task=task)
1617
1618
1619 def _foreman_spec_helper(spec):
1620 """Extend an entity spec by adding entries for all flat_names.
1621 Extract Ansible compatible argument_spec on the way.
1622 """
1623 foreman_spec = {}
1624 argument_spec = {}
1625
1626 _FILTER_SPEC_KEYS = {
1627 'ensure',
1628 'failsafe',
1629 'flat_name',
1630 'foreman_spec',
1631 'invisible',
1632 'optional_scope',
1633 'resolve',
1634 'resource_type',
1635 'scope',
1636 'search_by',
1637 'search_operator',
1638 'thin',
1639 'type',
1640 }
1641 _VALUE_SPEC_KEYS = {
1642 'ensure',
1643 'type',
1644 }
1645 _ENTITY_SPEC_KEYS = {
1646 'failsafe',
1647 'optional_scope',
1648 'resolve',
1649 'resource_type',
1650 'scope',
1651 'search_by',
1652 'search_operator',
1653 'thin',
1654 }
1655
1656 # _foreman_spec_helper() is called before we call check_requirements() in the __init__ of ForemanAnsibleModule
1657 # and thus before the if HAS APYPIE check happens.
1658 # We have to ensure that apypie is available before using it.
1659 # There is two cases where we can call _foreman_spec_helper() without apypie available:
1660 # * When the user calls the module but doesn't have the right Python libraries installed.
1661 # In this case nothing will works and the module will warn the user to install the required library.
1662 # * When Ansible generates docs from the argument_spec. As the inflector is only used to build foreman_spec and not argument_spec,
1663 # This is not a problem.
1664 #
1665 # So in conclusion, we only have to verify that apypie is available before using it.
1666 # Lazy evaluation helps there.
1667 for key, value in spec.items():
1668 foreman_value = {k: v for (k, v) in value.items() if k in _VALUE_SPEC_KEYS}
1669 argument_value = {k: v for (k, v) in value.items() if k not in _FILTER_SPEC_KEYS}
1670
1671 foreman_type = value.get('type')
1672 ansible_invisible = value.get('invisible', False)
1673 flat_name = value.get('flat_name')
1674
1675 if foreman_type == 'entity':
1676 if not flat_name:
1677 flat_name = '{0}_id'.format(key)
1678 foreman_value['resource_type'] = HAS_APYPIE and inflector.pluralize(key)
1679 foreman_value.update({k: v for (k, v) in value.items() if k in _ENTITY_SPEC_KEYS})
1680 elif foreman_type == 'entity_list':
1681 argument_value['type'] = 'list'
1682 argument_value['elements'] = value.get('elements', 'str')
1683 if not flat_name:
1684 flat_name = '{0}_ids'.format(HAS_APYPIE and inflector.singularize(key))
1685 foreman_value['resource_type'] = key
1686 foreman_value.update({k: v for (k, v) in value.items() if k in _ENTITY_SPEC_KEYS})
1687 elif foreman_type == 'nested_list':
1688 argument_value['type'] = 'list'
1689 argument_value['elements'] = 'dict'
1690 foreman_value['foreman_spec'], argument_value['options'] = _foreman_spec_helper(value['foreman_spec'])
1691 foreman_value['ensure'] = value.get('ensure', False)
1692 elif foreman_type:
1693 argument_value['type'] = foreman_type
1694
1695 if flat_name:
1696 foreman_value['flat_name'] = flat_name
1697 foreman_spec[flat_name] = {}
1698 # When translating to a flat name, the flattened entry should get the same "type"
1699 # as Ansible expects so that comparison still works for non-strings
1700 if argument_value.get('type') is not None:
1701 foreman_spec[flat_name]['type'] = argument_value['type']
1702
1703 foreman_spec[key] = foreman_value
1704
1705 if not ansible_invisible:
1706 argument_spec[key] = argument_value
1707
1708 return foreman_spec, argument_spec
1709
1710
1711 def _flatten_entity(entity, foreman_spec):
1712 """Flatten entity according to spec"""
1713 result = {}
1714 if entity is None:
1715 entity = {}
1716 for key, value in entity.items():
1717 if key in foreman_spec and foreman_spec[key].get('ensure', True) and value is not None:
1718 spec = foreman_spec[key]
1719 flat_name = spec.get('flat_name', key)
1720 property_type = spec.get('type', 'str')
1721 if property_type == 'entity':
1722 if value is not NoEntity:
1723 result[flat_name] = value['id']
1724 else:
1725 result[flat_name] = None
1726 elif property_type == 'entity_list':
1727 result[flat_name] = sorted(val['id'] for val in value)
1728 elif property_type == 'nested_list':
1729 result[flat_name] = [_flatten_entity(ent, foreman_spec[key]['foreman_spec']) for ent in value]
1730 else:
1731 result[flat_name] = value
1732 return result
1733
1734
1735 def _recursive_dict_without_none(a_dict, exclude=None):
1736 """
1737 Remove all entries with `None` value from a dict, recursively.
1738 Also drops all entries with keys in `exclude` in the top level.
1739 """
1740 if exclude is None:
1741 exclude = []
1742
1743 result = {}
1744
1745 for (k, v) in a_dict.items():
1746 if v is not None and k not in exclude:
1747 if isinstance(v, dict):
1748 v = _recursive_dict_without_none(v)
1749 elif isinstance(v, list) and v and isinstance(v[0], dict):
1750 v = [_recursive_dict_without_none(element) for element in v]
1751 result[k] = v
1752
1753 return result
1754
1755
1756 def _is_resolved(spec, what):
1757 if spec.get('type') not in ('entity', 'entity_list'):
1758 return True
1759
1760 if spec.get('type') == 'entity' and (what is None or isinstance(what, dict)):
1761 return True
1762
1763 if spec.get('type') == 'entity_list' and isinstance(what, list) and what and (what[0] is None or isinstance(what[0], dict)):
1764 return True
1765
1766 return False
1767
1768
1769 # Helper for (global, operatingsystem, ...) parameters
1770 def parameter_value_to_str(value, parameter_type):
1771 """Helper to convert the value of parameters to string according to their parameter_type."""
1772 if parameter_type in ['real', 'integer']:
1773 parameter_string = str(value)
1774 elif parameter_type in ['array', 'hash', 'yaml', 'json']:
1775 parameter_string = json.dumps(value, sort_keys=True)
1776 else:
1777 parameter_string = value
1778 return parameter_string
1779
1780
1781 # Helper for converting lists of parameters
1782 def parameters_list_to_str_list(parameters):
1783 filtered_params = []
1784 for param in parameters:
1785 if 'hidden_value?' in param:
1786 param['hidden_value'] = param.pop('hidden_value?')
1787 new_param = {k: v for (k, v) in param.items() if k in parameter_ansible_spec.keys()}
1788 new_param['value'] = parameter_value_to_str(new_param['value'], new_param.get('parameter_type', 'string'))
1789 filtered_params.append(new_param)
1790 return filtered_params
1791
1792
1793 # Helper for templates
1794 def parse_template(template_content, module):
1795 if not HAS_PYYAML:
1796 module.fail_json(msg=missing_required_lib("PyYAML"), exception=PYYAML_IMP_ERR)
1797
1798 try:
1799 template_dict = {}
1800 data = re.search(
1801 r'<%#([^%]*([^%]*%*[^>%])*%*)%>', template_content)
1802 if data:
1803 datalist = data.group(1)
1804 if datalist[-1] == '-':
1805 datalist = datalist[:-1]
1806 template_dict = yaml.safe_load(datalist)
1807 # No metadata, import template anyway
1808 template_dict['template'] = template_content
1809 except Exception as e:
1810 module.fail_json(msg='Error while parsing template: ' + to_native(e))
1811 return template_dict
1812
1813
1814 def parse_template_from_file(file_name, module):
1815 try:
1816 with open(file_name) as input_file:
1817 template_content = input_file.read()
1818 template_dict = parse_template(template_content, module)
1819 except Exception as e:
1820 module.fail_json(msg='Error while reading template file: ' + to_native(e))
1821 return template_dict
1822
1823
1824 # Helper for titles
1825 def split_fqn(title):
1826 """ Split fully qualified name (title) in name and parent title """
1827 fqn = title.split('/')
1828 if len(fqn) > 1:
1829 name = fqn.pop()
1830 return (name, '/'.join(fqn))
1831 else:
1832 return (title, None)
1833
1834
1835 def build_fqn(name, parent=None):
1836 if parent:
1837 return "%s/%s" % (parent, name)
1838 else:
1839 return name
1840
1841
1842 # Helper for puppetclasses
1843 def ensure_puppetclasses(module, entity_type, entity, expected_puppetclasses=None):
1844 if expected_puppetclasses is not None:
1845 puppetclasses_resource = '{0}_classes'.format(entity_type)
1846 expected_puppetclasses = module.find_puppetclasses(expected_puppetclasses, environment=entity['environment_id'], thin=True)
1847 current_puppetclasses = entity.get('puppetclasses', [])
1848 current_puppetclass_ids = [pc['id'] for pc in current_puppetclasses]
1849 previous_puppetclass_ids = current_puppetclass_ids[:]
1850 for puppetclass in expected_puppetclasses:
1851 if puppetclass['id'] in current_puppetclass_ids:
1852 # Nothing to do, prevent removal
1853 previous_puppetclass_ids.remove(puppetclass['id'])
1854 else:
1855 payload = {'{0}_id'.format(entity_type): entity['id'], 'puppetclass_id': puppetclass['id']}
1856 module.ensure_entity(puppetclasses_resource, {}, None, params=payload, state='present', foreman_spec={})
1857 # Add to entity for reporting
1858 current_puppetclass_ids.append(puppetclass['id'])
1859
1860 for leftover_puppetclass in previous_puppetclass_ids:
1861 payload = {'{0}_id'.format(entity_type): entity['id']}
1862 module.ensure_entity(
1863 puppetclasses_resource, {}, {'id': leftover_puppetclass},
1864 params=payload, state='absent', foreman_spec={},
1865 )
1866 current_puppetclass_ids.remove(leftover_puppetclass)
1867 entity['puppetclass_ids'] = current_puppetclass_ids
1868
1869
1870 # Helper constants
1871 OS_LIST = ['AIX',
1872 'Altlinux',
1873 'Archlinux',
1874 'Coreos',
1875 'Debian',
1876 'Fcos',
1877 'Freebsd',
1878 'Gentoo',
1879 'Junos',
1880 'NXOS',
1881 'Rancheros',
1882 'Redhat',
1883 'Rhcos',
1884 'Solaris',
1885 'Suse',
1886 'VRP',
1887 'Windows',
1888 'Xenserver',
1889 ]
1890
1891 TEMPLATE_KIND_LIST = [
1892 'Bootdisk',
1893 'cloud-init',
1894 'finish',
1895 'host_init_config',
1896 'iPXE',
1897 'job_template',
1898 'kexec',
1899 'POAP',
1900 'provision',
1901 'PXEGrub',
1902 'PXEGrub2',
1903 'PXELinux',
1904 'registration',
1905 'script',
1906 'user_data',
1907 'ZTP',
1908 ]
1909
1910 # interface specs
1911 interfaces_spec = dict(
1912 id=dict(invisible=True),
1913 mac=dict(),
1914 ip=dict(),
1915 ip6=dict(),
1916 type=dict(choices=['interface', 'bmc', 'bond', 'bridge']),
1917 name=dict(),
1918 subnet=dict(type='entity'),
1919 subnet6=dict(type='entity', resource_type='subnets'),
1920 domain=dict(type='entity'),
1921 identifier=dict(),
1922 managed=dict(type='bool'),
1923 primary=dict(type='bool'),
1924 provision=dict(type='bool'),
1925 execution=dict(type='bool'),
1926 username=dict(),
1927 password=dict(no_log=True),
1928 provider=dict(choices=['IPMI', 'Redfish', 'SSH']),
1929 virtual=dict(type='bool'),
1930 tag=dict(),
1931 mtu=dict(type='int'),
1932 attached_to=dict(),
1933 mode=dict(choices=[
1934 'balance-rr',
1935 'active-backup',
1936 'balance-xor',
1937 'broadcast',
1938 '802.3ad',
1939 'balance-tlb',
1940 'balance-alb',
1941 ]),
1942 attached_devices=dict(type='list', elements='str'),
1943 bond_options=dict(),
1944 compute_attributes=dict(type='dict'),
1945 )