-
Notifications
You must be signed in to change notification settings - Fork 167
/
foreman_helper.py
1894 lines (1574 loc) · 78.4 KB
/
foreman_helper.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# (c) Matthias Dellweg (ATIX AG) 2017
# pylint: disable=raise-missing-from
# pylint: disable=super-with-arguments
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import hashlib
import json
import os
import operator
import re
import time
import traceback
from contextlib import contextmanager
from collections import defaultdict
from functools import wraps
from ansible.module_utils.basic import AnsibleModule, missing_required_lib, env_fallback
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils import six
try:
from ansible_collections.theforeman.foreman.plugins.module_utils._version import LooseVersion
except ImportError:
from plugins.module_utils._version import LooseVersion
try:
try:
from ansible_collections.theforeman.foreman.plugins.module_utils import _apypie as apypie
except ImportError:
from plugins.module_utils import _apypie as apypie
import requests.exceptions
HAS_APYPIE = True
inflector = apypie.Inflector()
except ImportError:
HAS_APYPIE = False
APYPIE_IMP_ERR = traceback.format_exc()
try:
import yaml
HAS_PYYAML = True
except ImportError:
HAS_PYYAML = False
PYYAML_IMP_ERR = traceback.format_exc()
parameter_foreman_spec = dict(
id=dict(invisible=True),
name=dict(required=True),
value=dict(type='raw', required=True),
parameter_type=dict(default='string', choices=['string', 'boolean', 'integer', 'real', 'array', 'hash', 'yaml', 'json']),
)
parameter_ansible_spec = {k: v for (k, v) in parameter_foreman_spec.items() if k != 'id'}
_PLUGIN_RESOURCES = {
'ansible': 'ansible_roles',
'discovery': 'discovery_rules',
'katello': 'subscriptions',
'openscap': 'scap_contents',
'remote_execution': 'remote_execution_features',
'scc_manager': 'scc_accounts',
'snapshot_management': 'snapshots',
'templates': 'templates',
}
ENTITY_KEYS = dict(
hostgroups='title',
locations='title',
operatingsystems='title',
# TODO: Organizations should be search by title (as foreman allows nested orgs) but that's not the case ATM.
# Applying this will need to record a lot of tests that is out of scope for the moment.
# organizations='title',
scap_contents='title',
users='login',
)
class NoEntity(object):
pass
def _exception2fail_json(msg='Generic failure: {0}'):
"""
Decorator to convert Python exceptions into Ansible errors that can be reported to the user.
"""
def decor(f):
@wraps(f)
def inner(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
err_msg = "{0}: {1}".format(e.__class__.__name__, to_native(e))
self.fail_from_exception(e, msg.format(err_msg))
return inner
return decor
def _check_patch_needed(introduced_version=None, fixed_version=None, plugins=None):
"""
Decorator to check whether a specific apidoc patch is required.
:param introduced_version: The version of Foreman the API bug was introduced.
:type introduced_version: str, optional
:param fixed_version: The version of Foreman the API bug was fixed.
:type fixed_version: str, optional
:param plugins: Which plugins are required for this patch.
:type plugins: list, optional
"""
def decor(f):
@wraps(f)
def inner(self, *args, **kwargs):
if plugins is not None and not all(self.has_plugin(plugin) for plugin in plugins):
return
if fixed_version is not None and self.foreman_version >= LooseVersion(fixed_version):
return
if introduced_version is not None and self.foreman_version < LooseVersion(introduced_version):
return
return f(self, *args, **kwargs)
return inner
return decor
class KatelloMixin():
"""
Katello Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with Katello entities.
This includes:
* add a required ``organization`` parameter to the module
* add Katello to the list of required plugins
"""
def __init__(self, **kwargs):
foreman_spec = dict(
organization=dict(type='entity', required=True),
)
foreman_spec.update(kwargs.pop('foreman_spec', {}))
required_plugins = kwargs.pop('required_plugins', [])
required_plugins.append(('katello', ['*']))
super(KatelloMixin, self).__init__(foreman_spec=foreman_spec, required_plugins=required_plugins, **kwargs)
class TaxonomyMixin(object):
"""
Taxonomy Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with taxonomic entities.
This adds optional ``organizations`` and ``locations`` parameters to the module.
"""
def __init__(self, **kwargs):
foreman_spec = dict(
organizations=dict(type='entity_list'),
locations=dict(type='entity_list'),
)
foreman_spec.update(kwargs.pop('foreman_spec', {}))
super(TaxonomyMixin, self).__init__(foreman_spec=foreman_spec, **kwargs)
class ParametersMixinBase(object):
"""
Base Class for the Parameters Mixins.
Provides a function to verify no duplicate parameters are set.
"""
def validate_parameters(self):
parameters = self.foreman_params.get('parameters')
if parameters is not None:
parameter_names = [param['name'] for param in parameters]
duplicate_params = set([x for x in parameter_names if parameter_names.count(x) > 1])
if duplicate_params:
self.fail_json(msg="There are duplicate keys in 'parameters': {0}.".format(duplicate_params))
class ParametersMixin(ParametersMixinBase):
"""
Parameters Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with entities that support parameters.
This allows to submit parameters to Foreman in the same request as modifying the main entity, thus making the parameters
available to any action that might be triggered when the entity is saved.
By default, parametes are submited to the API using the ``<entity_name>_parameters_attributes`` key.
If you need to override this, set the ``PARAMETERS_FLAT_NAME`` attribute to the key that shall be used instead.
This adds optional ``parameters`` parameter to the module. It also enhances the ``run()`` method to properly handle the
provided parameters.
"""
def __init__(self, **kwargs):
self.entity_name = kwargs.pop('entity_name', self.entity_name_from_class)
parameters_flat_name = getattr(self, "PARAMETERS_FLAT_NAME", None) or '{0}_parameters_attributes'.format(self.entity_name)
foreman_spec = dict(
parameters=dict(type='list', elements='dict', options=parameter_ansible_spec, flat_name=parameters_flat_name),
)
foreman_spec.update(kwargs.pop('foreman_spec', {}))
super(ParametersMixin, self).__init__(foreman_spec=foreman_spec, **kwargs)
self.validate_parameters()
def run(self, **kwargs):
entity = self.lookup_entity('entity')
if not self.desired_absent:
if entity and 'parameters' in entity:
entity['parameters'] = parameters_list_to_str_list(entity['parameters'])
parameters = self.foreman_params.get('parameters')
if parameters is not None:
self.foreman_params['parameters'] = parameters_list_to_str_list(parameters)
return super(ParametersMixin, self).run(**kwargs)
class NestedParametersMixin(ParametersMixinBase):
"""
Nested Parameters Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with entities that support parameters,
but require them to be managed in separate API requests.
This adds optional ``parameters`` parameter to the module. It also enhances the ``run()`` method to properly handle the
provided parameters.
"""
def __init__(self, **kwargs):
foreman_spec = dict(
parameters=dict(type='nested_list', foreman_spec=parameter_foreman_spec),
)
foreman_spec.update(kwargs.pop('foreman_spec', {}))
super(NestedParametersMixin, self).__init__(foreman_spec=foreman_spec, **kwargs)
self.validate_parameters()
def run(self, **kwargs):
new_entity = super(NestedParametersMixin, self).run(**kwargs)
if new_entity:
scope = {'{0}_id'.format(self.entity_name): new_entity['id']}
self.ensure_scoped_parameters(scope)
return new_entity
def ensure_scoped_parameters(self, scope):
parameters = self.foreman_params.get('parameters')
if parameters is not None:
entity = self.lookup_entity('entity')
if self.state == 'present' or (self.state == 'present_with_defaults' and entity is None):
if entity:
current_parameters = {parameter['name']: parameter for parameter in self.list_resource('parameters', params=scope)}
else:
current_parameters = {}
desired_parameters = {parameter['name']: parameter for parameter in parameters}
for name in desired_parameters:
desired_parameter = desired_parameters[name]
desired_parameter['value'] = parameter_value_to_str(desired_parameter['value'], desired_parameter['parameter_type'])
current_parameter = current_parameters.pop(name, None)
if current_parameter:
if 'parameter_type' not in current_parameter:
current_parameter['parameter_type'] = 'string'
current_parameter['value'] = parameter_value_to_str(current_parameter['value'], current_parameter['parameter_type'])
self.ensure_entity(
'parameters', desired_parameter, current_parameter, state="present", foreman_spec=parameter_foreman_spec, params=scope)
for current_parameter in current_parameters.values():
self.ensure_entity(
'parameters', None, current_parameter, state="absent", foreman_spec=parameter_foreman_spec, params=scope)
class HostMixin(ParametersMixin):
"""
Host Mixin to extend a :class:`ForemanAnsibleModule` (or any subclass) to work with host-related entities (Hosts, Hostgroups).
This adds many optional parameters that are specific to Hosts and Hostgroups to the module.
It also includes :class:`ParametersMixin`.
"""
def __init__(self, **kwargs):
foreman_spec = dict(
compute_resource=dict(type='entity'),
compute_profile=dict(type='entity'),
domain=dict(type='entity'),
subnet=dict(type='entity'),
subnet6=dict(type='entity', resource_type='subnets'),
root_pass=dict(no_log=True),
realm=dict(type='entity'),
architecture=dict(type='entity'),
operatingsystem=dict(type='entity'),
medium=dict(aliases=['media'], type='entity'),
ptable=dict(type='entity'),
pxe_loader=dict(choices=['PXELinux BIOS', 'PXELinux UEFI', 'Grub UEFI', 'Grub2 BIOS', 'Grub2 ELF',
'Grub2 UEFI', 'Grub2 UEFI SecureBoot', 'Grub2 UEFI HTTP', 'Grub2 UEFI HTTPS',
'Grub2 UEFI HTTPS SecureBoot', 'iPXE Embedded', 'iPXE UEFI HTTP', 'iPXE Chain BIOS', 'iPXE Chain UEFI', 'None']),
environment=dict(type='entity'),
puppetclasses=dict(type='entity_list', resolve=False),
config_groups=dict(type='entity_list'),
puppet_proxy=dict(type='entity', resource_type='smart_proxies'),
puppet_ca_proxy=dict(type='entity', resource_type='smart_proxies'),
openscap_proxy=dict(type='entity', resource_type='smart_proxies'),
content_source=dict(type='entity', scope=['organization'], resource_type='smart_proxies'),
lifecycle_environment=dict(type='entity', scope=['organization']),
kickstart_repository=dict(type='entity', scope=['organization'], optional_scope=['lifecycle_environment', 'content_view'],
resource_type='repositories'),
content_view=dict(type='entity', scope=['organization'], optional_scope=['lifecycle_environment']),
activation_keys=dict(no_log=False),
)
foreman_spec.update(kwargs.pop('foreman_spec', {}))
required_plugins = kwargs.pop('required_plugins', []) + [
('katello', ['activation_keys', 'content_source', 'lifecycle_environment', 'kickstart_repository', 'content_view']),
('openscap', ['openscap_proxy']),
]
mutually_exclusive = kwargs.pop('mutually_exclusive', []) + [['medium', 'kickstart_repository']]
super(HostMixin, self).__init__(foreman_spec=foreman_spec, required_plugins=required_plugins, mutually_exclusive=mutually_exclusive, **kwargs)
def run(self, **kwargs):
entity = self.lookup_entity('entity')
if not self.desired_absent:
if 'activation_keys' in self.foreman_params:
if 'parameters' not in self.foreman_params:
parameters = [param for param in (entity or {}).get('parameters', []) if param['name'] != 'kt_activation_keys']
else:
parameters = self.foreman_params['parameters']
ak_param = {'name': 'kt_activation_keys', 'parameter_type': 'string', 'value': self.foreman_params.pop('activation_keys')}
self.foreman_params['parameters'] = parameters + [ak_param]
elif 'parameters' in self.foreman_params and entity is not None:
current_ak_param = next((param for param in entity.get('parameters') if param['name'] == 'kt_activation_keys'), None)
desired_ak_param = next((param for param in self.foreman_params['parameters'] if param['name'] == 'kt_activation_keys'), None)
if current_ak_param and desired_ak_param is None:
self.foreman_params['parameters'].append(current_ak_param)
self.validate_parameters()
return super(HostMixin, self).run(**kwargs)
class ForemanAnsibleModule(AnsibleModule):
""" Baseclass for all foreman related Ansible modules.
It handles connection parameters and adds the concept of the `foreman_spec`.
This adds automatic entities resolution based on provided attributes/ sub entities options.
It adds the following options to foreman_spec 'entity' and 'entity_list' types:
* search_by (str): Field used to search the sub entity. Defaults to 'name' unless `parent` was set, in which case it defaults to `title`.
* search_operator (str): Operator used to search the sub entity. Defaults to '='. For fuzzy search use '~'.
* resource_type (str): Resource type used to build API resource PATH. Defaults to pluralized entity key.
* resolve (boolean): Defaults to 'True'. If set to false, the sub entity will not be resolved automatically
* ensure (boolean): Defaults to 'True'. If set to false, it will be removed before sending data to the foreman server.
"""
def __init__(self, **kwargs):
# State recording for changed and diff reporting
self._changed = False
self._before = defaultdict(list)
self._after = defaultdict(list)
self._after_full = defaultdict(list)
self.foreman_spec, gen_args = _foreman_spec_helper(kwargs.pop('foreman_spec', {}))
argument_spec = dict(
server_url=dict(required=True, fallback=(env_fallback, ['FOREMAN_SERVER_URL', 'FOREMAN_SERVER', 'FOREMAN_URL'])),
username=dict(required=True, fallback=(env_fallback, ['FOREMAN_USERNAME', 'FOREMAN_USER'])),
password=dict(required=True, no_log=True, fallback=(env_fallback, ['FOREMAN_PASSWORD'])),
validate_certs=dict(type='bool', default=True, fallback=(env_fallback, ['FOREMAN_VALIDATE_CERTS'])),
)
argument_spec.update(gen_args)
argument_spec.update(kwargs.pop('argument_spec', {}))
supports_check_mode = kwargs.pop('supports_check_mode', True)
self.required_plugins = kwargs.pop('required_plugins', [])
super(ForemanAnsibleModule, self).__init__(argument_spec=argument_spec, supports_check_mode=supports_check_mode, **kwargs)
aliases = {alias for arg in argument_spec.values() for alias in arg.get('aliases', [])}
self.foreman_params = _recursive_dict_without_none(self.params, aliases)
self.check_requirements()
self._foremanapi_server_url = self.foreman_params.pop('server_url')
self._foremanapi_username = self.foreman_params.pop('username')
self._foremanapi_password = self.foreman_params.pop('password')
self._foremanapi_validate_certs = self.foreman_params.pop('validate_certs')
if self._foremanapi_server_url.lower().startswith('http://'):
self.warn("You have configured a plain HTTP server URL. All communication will happen unencrypted.")
elif not self._foremanapi_server_url.lower().startswith('https://'):
self.fail_json(msg="The server URL needs to be either HTTPS or HTTP!")
self.task_timeout = 60
self.task_poll = 4
self._thin_default = False
self.state = 'undefined'
@contextmanager
def api_connection(self):
"""
Execute a given code block after connecting to the API.
When the block has finished, call :func:`exit_json` to report that the module has finished to Ansible.
"""
self.connect()
yield
self.exit_json()
@property
def changed(self):
return self._changed
def set_changed(self):
self._changed = True
def _patch_host_update(self):
_host_methods = self.foremanapi.apidoc['docs']['resources']['hosts']['methods']
_host_update = next(x for x in _host_methods if x['name'] == 'update')
for param in ['location_id', 'organization_id']:
_host_update_taxonomy_param = next(x for x in _host_update['params'] if x['name'] == param)
_host_update['params'].remove(_host_update_taxonomy_param)
@_check_patch_needed(fixed_version='2.0.0')
def _patch_templates_resource_name(self):
"""
Need to support both singular and plural form.
Not checking for the templates plugin here, as the check relies on the new name.
The resource was made plural per https://projects.theforeman.org/issues/28750
"""
if 'template' in self.foremanapi.apidoc['docs']['resources']:
self.foremanapi.apidoc['docs']['resources']['templates'] = self.foremanapi.apidoc['docs']['resources']['template']
@_check_patch_needed(fixed_version='1.23.0')
def _patch_location_api(self):
"""This is a workaround for the broken taxonomies apidoc in foreman.
see https://projects.theforeman.org/issues/10359
"""
_location_organizations_parameter = {
u'validations': [],
u'name': u'organization_ids',
u'show': True,
u'description': u'\n<p>Organization IDs</p>\n',
u'required': False,
u'allow_nil': True,
u'allow_blank': False,
u'full_name': u'location[organization_ids]',
u'expected_type': u'array',
u'metadata': None,
u'validator': u'',
}
_location_methods = self.foremanapi.apidoc['docs']['resources']['locations']['methods']
_location_create = next(x for x in _location_methods if x['name'] == 'create')
_location_create_params_location = next(x for x in _location_create['params'] if x['name'] == 'location')
_location_create_params_location['params'].append(_location_organizations_parameter)
_location_update = next(x for x in _location_methods if x['name'] == 'update')
_location_update_params_location = next(x for x in _location_update['params'] if x['name'] == 'location')
_location_update_params_location['params'].append(_location_organizations_parameter)
@_check_patch_needed(fixed_version='2.2.0', plugins=['remote_execution'])
def _patch_subnet_rex_api(self):
"""
This is a workaround for the broken subnet apidoc in foreman remote execution.
See https://projects.theforeman.org/issues/19086 and https://projects.theforeman.org/issues/30651
"""
_subnet_rex_proxies_parameter = {
u'validations': [],
u'name': u'remote_execution_proxy_ids',
u'show': True,
u'description': u'\n<p>Remote Execution Proxy IDs</p>\n',
u'required': False,
u'allow_nil': True,
u'allow_blank': False,
u'full_name': u'subnet[remote_execution_proxy_ids]',
u'expected_type': u'array',
u'metadata': None,
u'validator': u'',
}
_subnet_methods = self.foremanapi.apidoc['docs']['resources']['subnets']['methods']
_subnet_create = next(x for x in _subnet_methods if x['name'] == 'create')
_subnet_create_params_subnet = next(x for x in _subnet_create['params'] if x['name'] == 'subnet')
_subnet_create_params_subnet['params'].append(_subnet_rex_proxies_parameter)
_subnet_update = next(x for x in _subnet_methods if x['name'] == 'update')
_subnet_update_params_subnet = next(x for x in _subnet_update['params'] if x['name'] == 'subnet')
_subnet_update_params_subnet['params'].append(_subnet_rex_proxies_parameter)
@_check_patch_needed(introduced_version='2.1.0', fixed_version='2.3.0')
def _patch_subnet_externalipam_group_api(self):
"""
This is a workaround for the broken subnet apidoc for External IPAM.
See https://projects.theforeman.org/issues/30890
"""
_subnet_externalipam_group_parameter = {
u'validations': [],
u'name': u'externalipam_group',
u'show': True,
u'description': u'\n<p>External IPAM group - only relevant when IPAM is set to external</p>\n',
u'required': False,
u'allow_nil': True,
u'allow_blank': False,
u'full_name': u'subnet[externalipam_group]',
u'expected_type': u'string',
u'metadata': None,
u'validator': u'',
}
_subnet_methods = self.foremanapi.apidoc['docs']['resources']['subnets']['methods']
_subnet_create = next(x for x in _subnet_methods if x['name'] == 'create')
_subnet_create_params_subnet = next(x for x in _subnet_create['params'] if x['name'] == 'subnet')
_subnet_create_params_subnet['params'].append(_subnet_externalipam_group_parameter)
_subnet_update = next(x for x in _subnet_methods if x['name'] == 'update')
_subnet_update_params_subnet = next(x for x in _subnet_update['params'] if x['name'] == 'subnet')
_subnet_update_params_subnet['params'].append(_subnet_externalipam_group_parameter)
@_check_patch_needed(fixed_version='1.24.0', plugins=['katello'])
def _patch_content_uploads_update_api(self):
"""
This is a workaround for the broken content_uploads update apidoc in Katello.
See https://projects.theforeman.org/issues/27590
"""
_content_upload_methods = self.foremanapi.apidoc['docs']['resources']['content_uploads']['methods']
_content_upload_update = next(x for x in _content_upload_methods if x['name'] == 'update')
_content_upload_update_params_id = next(x for x in _content_upload_update['params'] if x['name'] == 'id')
_content_upload_update_params_id['expected_type'] = 'string'
_content_upload_destroy = next(x for x in _content_upload_methods if x['name'] == 'destroy')
_content_upload_destroy_params_id = next(x for x in _content_upload_destroy['params'] if x['name'] == 'id')
_content_upload_destroy_params_id['expected_type'] = 'string'
@_check_patch_needed(plugins=['katello'])
def _patch_organization_update_api(self):
"""
This is a workaround for the broken organization update apidoc in Katello.
See https://projects.theforeman.org/issues/27538
"""
_organization_methods = self.foremanapi.apidoc['docs']['resources']['organizations']['methods']
_organization_update = next(x for x in _organization_methods if x['name'] == 'update')
_organization_update_params_organization = next(x for x in _organization_update['params'] if x['name'] == 'organization')
_organization_update_params_organization['required'] = False
@_check_patch_needed(fixed_version='1.24.0', plugins=['katello'])
def _patch_subscription_index_api(self):
"""
This is a workaround for the broken subscriptions apidoc in Katello.
See https://projects.theforeman.org/issues/27575
"""
_subscription_methods = self.foremanapi.apidoc['docs']['resources']['subscriptions']['methods']
_subscription_index = next(x for x in _subscription_methods if x['name'] == 'index')
_subscription_index_params_organization_id = next(x for x in _subscription_index['params'] if x['name'] == 'organization_id')
_subscription_index_params_organization_id['required'] = False
@_check_patch_needed(fixed_version='1.24.0', plugins=['katello'])
def _patch_sync_plan_api(self):
"""
This is a workaround for the broken sync_plan apidoc in Katello.
See https://projects.theforeman.org/issues/27532
"""
_organization_parameter = {
u'validations': [],
u'name': u'organization_id',
u'show': True,
u'description': u'\n<p>Filter sync plans by organization name or label</p>\n',
u'required': False,
u'allow_nil': False,
u'allow_blank': False,
u'full_name': u'organization_id',
u'expected_type': u'numeric',
u'metadata': None,
u'validator': u'Must be a number.',
}
_sync_plan_methods = self.foremanapi.apidoc['docs']['resources']['sync_plans']['methods']
_sync_plan_add_products = next(x for x in _sync_plan_methods if x['name'] == 'add_products')
if next((x for x in _sync_plan_add_products['params'] if x['name'] == 'organization_id'), None) is None:
_sync_plan_add_products['params'].append(_organization_parameter)
_sync_plan_remove_products = next(x for x in _sync_plan_methods if x['name'] == 'remove_products')
if next((x for x in _sync_plan_remove_products['params'] if x['name'] == 'organization_id'), None) is None:
_sync_plan_remove_products['params'].append(_organization_parameter)
@_check_patch_needed(plugins=['katello'])
def _patch_cv_filter_rule_api(self):
"""
This is a workaround for missing params of CV Filter Rule update controller in Katello.
See https://projects.theforeman.org/issues/30908
"""
_content_view_filter_rule_methods = self.foremanapi.apidoc['docs']['resources']['content_view_filter_rules']['methods']
_content_view_filter_rule_create = next(x for x in _content_view_filter_rule_methods if x['name'] == 'create')
_content_view_filter_rule_update = next(x for x in _content_view_filter_rule_methods if x['name'] == 'update')
for param_name in ['uuid', 'errata_ids', 'date_type', 'module_stream_ids']:
create_param = next((x for x in _content_view_filter_rule_create['params'] if x['name'] == param_name), None)
update_param = next((x for x in _content_view_filter_rule_update['params'] if x['name'] == param_name), None)
if create_param is not None and update_param is None:
_content_view_filter_rule_update['params'].append(create_param)
def check_requirements(self):
if not HAS_APYPIE:
self.fail_json(msg=missing_required_lib("requests"), exception=APYPIE_IMP_ERR)
@_exception2fail_json(msg="Failed to connect to Foreman server: {0}")
def connect(self):
"""
Connect to the Foreman API.
This will create a new ``apypie.Api`` instance using the provided server information,
check that the API is actually reachable (by calling :func:`status`),
apply any required patches to the apidoc and ensure the server has all the plugins installed
that are required by the module.
"""
self.foremanapi = apypie.Api(
uri=self._foremanapi_server_url,
username=to_bytes(self._foremanapi_username),
password=to_bytes(self._foremanapi_password),
api_version=2,
verify_ssl=self._foremanapi_validate_certs,
)
_status = self.status()
self.foreman_version = LooseVersion(_status.get('version', '0.0.0'))
self.apply_apidoc_patches()
self.check_required_plugins()
def apply_apidoc_patches(self):
"""
Apply patches to the local apidoc representation.
When adding another patch, consider that the endpoint in question may depend on a plugin to be available.
If possible, make the patch only execute on specific server/plugin versions.
"""
self._patch_host_update()
self._patch_templates_resource_name()
self._patch_location_api()
self._patch_subnet_rex_api()
self._patch_subnet_externalipam_group_api()
# Katello
self._patch_content_uploads_update_api()
self._patch_organization_update_api()
self._patch_subscription_index_api()
self._patch_sync_plan_api()
self._patch_cv_filter_rule_api()
@_exception2fail_json(msg="Failed to connect to Foreman server: {0}")
def status(self):
"""
Call the ``status`` API endpoint to ensure the server is reachable.
:return: The full API response
:rtype: dict
"""
return self.foremanapi.resource('home').call('status')
def _resource(self, resource):
if resource not in self.foremanapi.resources:
raise Exception("The server doesn't know about {0}, is the right plugin installed?".format(resource))
return self.foremanapi.resource(resource)
def _resource_call(self, resource, *args, **kwargs):
return self._resource(resource).call(*args, **kwargs)
def _resource_prepare_params(self, resource, action, params):
api_action = self._resource(resource).action(action)
return api_action.prepare_params(params)
@_exception2fail_json(msg='Failed to show resource: {0}')
def show_resource(self, resource, resource_id, params=None):
"""
Execute the ``show`` action on an entity.
:param resource: Plural name of the api resource to show
:type resource: str
:param resource_id: The ID of the entity to show
:type resource_id: int
:param params: Lookup parameters (i.e. parent_id for nested entities)
:type params: Union[dict,None], optional
"""
if params is None:
params = {}
else:
params = params.copy()
params['id'] = resource_id
params = self._resource_prepare_params(resource, 'show', params)
return self._resource_call(resource, 'show', params)
@_exception2fail_json(msg='Failed to list resource: {0}')
def list_resource(self, resource, search=None, params=None):
"""
Execute the ``index`` action on an resource.
:param resource: Plural name of the api resource to show
:type resource: str
:param search: Search string as accepted by the API to limit the results
:type search: str, optional
:param params: Lookup parameters (i.e. parent_id for nested entities)
:type params: Union[dict,None], optional
"""
if params is None:
params = {}
else:
params = params.copy()
if search is not None:
params['search'] = search
params['per_page'] = 2 << 31
params = self._resource_prepare_params(resource, 'index', params)
return self._resource_call(resource, 'index', params)['results']
def find_resource(self, resource, search, params=None, failsafe=False, thin=None):
list_params = {}
if params is not None:
list_params.update(params)
if thin is None:
thin = self._thin_default
list_params['thin'] = thin
results = self.list_resource(resource, search, list_params)
if len(results) == 1:
result = results[0]
elif failsafe:
result = None
else:
if len(results) > 1:
error_msg = "too many ({0})".format(len(results))
else:
error_msg = "no"
self.fail_json(msg="Found {0} results while searching for {1} with {2}".format(error_msg, resource, search))
if result and not thin:
result = self.show_resource(resource, result['id'], params=params)
return result
def find_resource_by(self, resource, search_field, value, **kwargs):
if not value:
return NoEntity
search = '{0}{1}"{2}"'.format(search_field, kwargs.pop('search_operator', '='), value)
return self.find_resource(resource, search, **kwargs)
def find_resource_by_name(self, resource, name, **kwargs):
return self.find_resource_by(resource, 'name', name, **kwargs)
def find_resource_by_title(self, resource, title, **kwargs):
return self.find_resource_by(resource, 'title', title, **kwargs)
def find_resource_by_id(self, resource, obj_id, **kwargs):
return self.find_resource_by(resource, 'id', obj_id, **kwargs)
def find_resources_by_name(self, resource, names, **kwargs):
return [self.find_resource_by_name(resource, name, **kwargs) for name in names]
def find_operatingsystem(self, name, failsafe=False, **kwargs):
result = self.find_resource_by_title('operatingsystems', name, failsafe=True, **kwargs)
if not result:
result = self.find_resource_by('operatingsystems', 'title', name, search_operator='~', failsafe=failsafe, **kwargs)
return result
def find_puppetclass(self, name, environment=None, params=None, failsafe=False, thin=None):
if thin is None:
thin = self._thin_default
if environment:
scope = {'environment_id': environment}
else:
scope = {}
if params is not None:
scope.update(params)
search = 'name="{0}"'.format(name)
results = self.list_resource('puppetclasses', search, params=scope)
# verify that only one puppet module is returned with only one puppet class inside
# as provided search results have to be like "results": { "ntp": [{"id": 1, "name": "ntp" ...}]}
# and get the puppet class id
if len(results) == 1 and len(list(results.values())[0]) == 1:
result = list(results.values())[0][0]
if thin:
return {'id': result['id']}
else:
return result
if failsafe:
return None
else:
self.fail_json(msg='No data found for name="%s"' % search)
def find_puppetclasses(self, names, **kwargs):
return [self.find_puppetclass(name, **kwargs) for name in names]
def find_cluster(self, name, compute_resource):
cluster = self.find_compute_resource_parts('clusters', name, compute_resource, None, ['ovirt', 'vmware'])
# workaround for https://projects.theforeman.org/issues/31874
if compute_resource['provider'].lower() == 'vmware':
cluster['_api_identifier'] = cluster['name']
else:
cluster['_api_identifier'] = cluster['id']
return cluster
def find_network(self, name, compute_resource, cluster=None):
return self.find_compute_resource_parts('networks', name, compute_resource, cluster, ['ovirt', 'vmware', 'google', 'azurerm'])
def find_storage_domain(self, name, compute_resource, cluster=None):
return self.find_compute_resource_parts('storage_domains', name, compute_resource, cluster, ['ovirt', 'vmware'])
def find_storage_pod(self, name, compute_resource, cluster=None):
return self.find_compute_resource_parts('storage_pods', name, compute_resource, cluster, ['vmware'])
def find_compute_resource_parts(self, part_name, name, compute_resource, cluster=None, supported_crs=None):
if supported_crs is None:
supported_crs = []
if compute_resource['provider'].lower() not in supported_crs:
return {'id': name, 'name': name}
additional_params = {'id': compute_resource['id']}
if cluster is not None:
additional_params['cluster_id'] = cluster['_api_identifier']
api_name = 'available_{0}'.format(part_name)
available_parts = self.resource_action('compute_resources', api_name, params=additional_params,
ignore_check_mode=True, record_change=False)['results']
part = next((part for part in available_parts if str(part['name']) == str(name) or str(part['id']) == str(name)), None)
if part is None:
err_msg = "Could not find {0} '{1}' on compute resource '{2}'.".format(part_name, name, compute_resource.get('name'))
self.fail_json(msg=err_msg)
return part
def scope_for(self, key, scoped_resource=None):
# workaround for https://projects.theforeman.org/issues/31714
if scoped_resource in ['content_views', 'repositories'] and key == 'lifecycle_environment':
scope_key = 'environment'
else:
scope_key = key
return {'{0}_id'.format(scope_key): self.lookup_entity(key)['id']}
def set_entity(self, key, entity):
self.foreman_params[key] = entity
def lookup_entity(self, key, params=None):
if key not in self.foreman_params:
return None
entity_spec = self.foreman_spec[key]
if _is_resolved(entity_spec, self.foreman_params[key]):
# Already looked up or not an entity(_list) so nothing to do
return self.foreman_params[key]
result = self._lookup_entity(self.foreman_params[key], entity_spec, params)
self.set_entity(key, result)
return result
def _lookup_entity(self, identifier, entity_spec, params=None):
resource_type = entity_spec['resource_type']
failsafe = entity_spec.get('failsafe', False)
thin = entity_spec.get('thin', True)
if params:
params = params.copy()
else:
params = {}
try:
for scope in entity_spec.get('scope', []):
params.update(self.scope_for(scope, resource_type))
for optional_scope in entity_spec.get('optional_scope', []):
if optional_scope in self.foreman_params:
params.update(self.scope_for(optional_scope, resource_type))
except TypeError:
if failsafe:
if entity_spec.get('type') == 'entity':
result = None
else:
result = [None for value in identifier]
else:
self.fail_json(msg="Failed to lookup scope {0} while searching for {1}.".format(entity_spec['scope'], resource_type))
else:
# No exception happend => scope is in place
if resource_type == 'operatingsystems':
if entity_spec.get('type') == 'entity':
result = self.find_operatingsystem(identifier, params=params, failsafe=failsafe, thin=thin)
else:
result = [self.find_operatingsystem(value, params=params, failsafe=failsafe, thin=thin) for value in identifier]
elif resource_type == 'puppetclasses':
if entity_spec.get('type') == 'entity':
result = self.find_puppetclass(identifier, params=params, failsafe=failsafe, thin=thin)
else:
result = [self.find_puppetclass(value, params=params, failsafe=failsafe, thin=thin) for value in identifier]
else:
if entity_spec.get('type') == 'entity':
result = self.find_resource_by(
resource=resource_type,
value=identifier,
search_field=entity_spec.get('search_by', ENTITY_KEYS.get(resource_type, 'name')),
search_operator=entity_spec.get('search_operator', '='),
failsafe=failsafe, thin=thin, params=params,
)
else:
result = [self.find_resource_by(
resource=resource_type,
value=value,
search_field=entity_spec.get('search_by', ENTITY_KEYS.get(resource_type, 'name')),
search_operator=entity_spec.get('search_operator', '='),
failsafe=failsafe, thin=thin, params=params,
) for value in identifier]
return result
def auto_lookup_entities(self):
self.auto_lookup_nested_entities()
return [
self.lookup_entity(key)
for key, entity_spec in self.foreman_spec.items()
if entity_spec.get('resolve', True) and entity_spec.get('type') in {'entity', 'entity_list'}
]
def auto_lookup_nested_entities(self):
for key, entity_spec in self.foreman_spec.items():
if entity_spec.get('type') in {'nested_list'}:
for nested_key, nested_spec in entity_spec['foreman_spec'].items():
for item in self.foreman_params.get(key, []):
if (nested_key in item and nested_spec.get('resolve', True)
and not _is_resolved(nested_spec, item[nested_key])):
item[nested_key] = self._lookup_entity(item[nested_key], nested_spec)
def record_before(self, resource, entity):
self._before[resource].append(entity)
def record_after(self, resource, entity):
self._after[resource].append(entity)
def record_after_full(self, resource, entity):
self._after_full[resource].append(entity)
@_exception2fail_json(msg='Failed to ensure entity state: {0}')
def ensure_entity(self, resource, desired_entity, current_entity, params=None, state=None, foreman_spec=None):
"""
Ensure that a given entity has a certain state
:param resource: Plural name of the api resource to manipulate
:type resource: str
:param desired_entity: Desired properties of the entity
:type desired_entity: dict
:param current_entity: Current properties of the entity or None if nonexistent
:type current_entity: Union[dict,None]
:param params: Lookup parameters (i.e. parent_id for nested entities)
:type params: dict, optional
:param state: Desired state of the entity (optionally taken from the module)
:type state: str, optional
:param foreman_spec: Description of the entity structure (optionally taken from module)
:type foreman_spec: dict, optional
:return: The new current state of the entity
:rtype: Union[dict,None]
"""
if state is None:
state = self.state
if foreman_spec is None:
foreman_spec = self.foreman_spec
else:
foreman_spec, _dummy = _foreman_spec_helper(foreman_spec)
updated_entity = None
self.record_before(resource, _flatten_entity(current_entity, foreman_spec))
if state == 'present_with_defaults':
if current_entity is None:
updated_entity = self._create_entity(resource, desired_entity, params, foreman_spec)
elif state == 'present':
if current_entity is None:
updated_entity = self._create_entity(resource, desired_entity, params, foreman_spec)
else:
updated_entity = self._update_entity(resource, desired_entity, current_entity, params, foreman_spec)
elif state == 'copied':
if current_entity is not None:
updated_entity = self._copy_entity(resource, desired_entity, current_entity, params)
elif state == 'reverted':