Debian Codegraph @

ansible_collections/theforeman/foreman/plugins/modules/activation_key.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # (c) 2017, Andrew Kofink <[email protected]>
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import absolute_import, division, print_function
19 __metaclass__ = type
20
21
22 DOCUMENTATION = '''
23 ---
24 module: activation_key
25 version_added: 1.0.0
26 short_description: Manage Activation Keys
27 description:
28 - Create and manage activation keys
29 author: "Andrew Kofink (@akofink)"
30 options:
31 name:
32 description:
33 - Name of the activation key
34 required: true
35 type: str
36 description:
37 description:
38 - Description of the activation key
39 type: str
40 lifecycle_environment:
41 description:
42 - Name of the lifecycle environment
43 type: str
44 content_view:
45 description:
46 - Name of the content view
47 type: str
48 content_view_environments:
49 description:
50 - List of content view environments to add to activation key.
51 - Mutually exclusive with C(content_view) and C(lifecycle_environment).
52 type: list
53 elements: str
54 version_added: 5.8.0
55 subscriptions:
56 description:
57 - List of subscriptions that include either Name, Pool ID, or Upstream Pool ID.
58 - Pool IDs are preferred since Names and Upstream Pool IDs are not guaranteed to be unique. The module will fail if it finds more than one match.
59 - This parameter is not supported in SCA mode.
60 type: list
61 elements: dict
62 suboptions:
63 name:
64 description:
65 - Name of the Subscription to be added.
66 - Mutually exclusive with I(pool_id) and I(upstream_pool_id).
67 type: str
68 required: false
69 pool_id:
70 description:
71 - Pool ID of the Subscription to be added.
72 - Mutually exclusive with I(name) and I(upstream_pool_id).
73 - Also named C(Candlepin Id) in the CSV export of the subscriptions,
74 - it is as well the C(UUID) as output by C(hammer subscription list).
75 type: str
76 required: false
77 upstream_pool_id:
78 description:
79 - Upstream Pool ID of the Subscription to be added.
80 - Mutually exclusive with I(name) and I(pool_id).
81 - Also named C(Master Pools) in the Red Hat Portal.
82 type: str
83 required: false
84 host_collections:
85 description:
86 - List of host collections to add to activation key
87 type: list
88 elements: str
89 content_overrides:
90 description:
91 - List of content overrides that include label and override state
92 - Label refers to repository C(content_label).
93 - For Red Hat products for example C(rhel-7-server-rpms).
94 - For custom products it's in the format C(<organization_label>_<product_label>_<repository_label>), e.g. C(ExampleOrg_ExampleProduct_ExampleRepository).
95 - Override state ('enabled', 'disabled', or 'default') sets initial state of repository for newly registered hosts
96 type: list
97 elements: dict
98 suboptions:
99 label:
100 description:
101 - Repository C(content_label) to override when registering hosts with the activation key
102 type: str
103 required: true
104 override:
105 description:
106 - Override value to use for the repository when registering hosts with the activation key
107 choices:
108 - enabled
109 - disabled
110 - default
111 type: str
112 required: true
113 auto_attach:
114 description:
115 - Set Auto-Attach on or off
116 - The C(auto_attach) parameter is deprecated since Katello 4.13 and not available after Katello 4.19
117 type: bool
118 release_version:
119 description:
120 - Set the content release version
121 type: str
122 service_level:
123 description:
124 - Set the service level
125 choices:
126 - Self-Support
127 - Standard
128 - Premium
129 type: str
130 max_hosts:
131 description:
132 - Maximum number of registered content hosts.
133 - Required if I(unlimited_hosts=false)
134 type: int
135 unlimited_hosts:
136 description:
137 - Can the activation key have unlimited hosts
138 type: bool
139 purpose_usage:
140 description:
141 - Sets the system purpose usage
142 type: str
143 purpose_role:
144 description:
145 - Sets the system purpose role
146 type: str
147 purpose_addons:
148 description:
149 - Sets the system purpose add-ons
150 type: list
151 elements: str
152 state:
153 description:
154 - State of the Activation Key
155 - If C(copied) the key will be copied to a new one with I(new_name) as the name and all other fields left untouched
156 - C(present_with_defaults) will ensure the entity exists, but won't update existing ones
157 default: present
158 choices:
159 - present
160 - present_with_defaults
161 - absent
162 - copied
163 type: str
164 new_name:
165 description:
166 - Name of the new activation key when state == copied
167 type: str
168 extends_documentation_fragment:
169 - theforeman.foreman.foreman
170 - theforeman.foreman.foreman.organization
171 '''
172
173 EXAMPLES = '''
174 - name: "Create client activation key"
175 theforeman.foreman.activation_key:
176 username: "admin"
177 password: "changeme"
178 server_url: "https://foreman.example.com"
179 name: "Clients"
180 organization: "Default Organization"
181 lifecycle_environment: "Library"
182 content_view: 'client content view'
183 host_collections:
184 - rhel7-servers
185 - rhel7-production
186 content_overrides:
187 - label: rhel-7-server-rpms
188 override: enabled
189 - label: ExampleOrganization_ExampleCustomProduct_ExampleRepository
190 override: enabled
191 release_version: 7Server
192 service_level: Standard
193
194 - name: "Create client activation key with multiple content views"
195 theforeman.foreman.activation_key:
196 username: "admin"
197 password: "changeme"
198 server_url: "https://foreman.example.com"
199 name: "Clients"
200 organization: "Default Organization"
201 content_view_environments:
202 - prod/base_rhel_9
203 - test/third_party
204 host_collections:
205 - rhel9-servers
206 - rhel9-production
207 - rhel9-third-party-test
208 auto_attach: false
209 release_version: 9
210 service_level: Standard
211 '''
212
213 RETURN = '''
214 entity:
215 description: Final state of the affected entities grouped by their type.
216 returned: success
217 type: dict
218 contains:
219 activation_keys:
220 description: List of activation keys.
221 type: list
222 elements: dict
223 '''
224
225 from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule, PER_PAGE
226
227
228 def override_to_boolnone(override):
229 value = None
230 if isinstance(override, bool):
231 value = override
232 else:
233 override = override.lower()
234 if override == 'enabled':
235 value = True
236 elif override == 'disabled':
237 value = False
238 elif override == 'default':
239 value = None
240 return value
241
242
243 class KatelloActivationKeyModule(KatelloEntityAnsibleModule):
244 pass
245
246
247 def main():
248 module = KatelloActivationKeyModule(
249 foreman_spec=dict(
250 name=dict(required=True),
251 new_name=dict(),
252 description=dict(),
253 lifecycle_environment=dict(type='entity', flat_name='environment_id', scope=['organization']),
254 content_view=dict(type='entity', scope=['organization']),
255 content_view_environments=dict(type='list', elements='str'),
256 host_collections=dict(type='entity_list', scope=['organization']),
257 auto_attach=dict(type='bool'),
258 release_version=dict(),
259 service_level=dict(choices=['Self-Support', 'Standard', 'Premium']),
260 max_hosts=dict(type='int'),
261 unlimited_hosts=dict(type='bool'),
262 purpose_usage=dict(),
263 purpose_role=dict(),
264 purpose_addons=dict(type='list', elements='str'),
265 ),
266 mutually_exclusive=[
267 ['lifecycle_environment', 'content_view_environments'],
268 ['content_view', 'content_view_environments']
269 ],
270 argument_spec=dict(
271 subscriptions=dict(type='list', elements='dict', options=dict(
272 name=dict(),
273 pool_id=dict(),
274 upstream_pool_id=dict(),
275 ),
276 required_one_of=[['name', 'pool_id', 'upstream_pool_id']],
277 mutually_exclusive=[['name', 'pool_id', 'upstream_pool_id']],
278 ),
279 content_overrides=dict(type='list', elements='dict', options=dict(
280 label=dict(required=True),
281 override=dict(required=True, choices=['enabled', 'disabled', 'default']),
282 )),
283 state=dict(default='present', choices=['present', 'present_with_defaults', 'absent', 'copied']),
284 ),
285 required_if=[
286 ['state', 'copied', ['new_name']],
287 ['unlimited_hosts', False, ['max_hosts']],
288 ],
289 )
290
291 with module.api_connection():
292 entity = module.lookup_entity('entity')
293 scope = module.scope_for('organization')
294
295 if module.state == 'copied':
296 new_entity = module.find_resource_by_name('activation_keys', name=module.foreman_params['new_name'], params=scope, failsafe=True)
297 if new_entity is not None:
298 module.warn("Activation Key '{0}' already exists.".format(module.foreman_params['new_name']))
299 module.exit_json()
300
301 subscriptions = module.foreman_params.pop('subscriptions', None)
302 content_overrides = module.foreman_params.pop('content_overrides', None)
303 if not module.desired_absent:
304 module.lookup_entity('host_collections')
305 host_collections = module.foreman_params.pop('host_collections', None)
306
307 content_view_environments = module.foreman_params.pop('content_view_environments', None)
308 content_view = module.foreman_params.get("content_view")
309 lifecycle_environment = module.foreman_params.get("lifecycle_environment")
310 # only use content view environments if content view and lifecycle environment are not specified
311 if content_view_environments is not None and content_view is None and lifecycle_environment is None:
312 desired_content_view_environments = set(content_view_environments)
313 if not entity:
314 current_content_view_environments = set()
315 else:
316 current_content_view_environments = set(entity.get('content_view_environment_labels', '').split(","))
317 if desired_content_view_environments != current_content_view_environments:
318 module.foreman_params["content_view_environments"] = sorted(list(desired_content_view_environments))
319
320 activation_key = module.run()
321
322 # only update subscriptions of newly created or updated AKs
323 # copied keys inherit the subscriptions of the origin, so one would not have to specify them again
324 # deleted keys don't need subscriptions anymore either
325 if module.state == 'present' or (module.state == 'present_with_defaults' and module.changed):
326 # the auto_attach, release_version and service_level parameters can only be set on an existing AK with an update,
327 # not during create, so let's force an update. see https://projects.theforeman.org/issues/27632 for details
328 if any(key in module.foreman_params for key in ['auto_attach', 'release_version', 'service_level']) and module.changed:
329 activation_key = module.ensure_entity('activation_keys', module.foreman_params, activation_key, params=scope)
330
331 ak_scope = {'activation_key_id': activation_key['id']}
332 ak_scope.update(scope)
333 if subscriptions is not None:
334 desired_subscriptions = []
335 for subscription in subscriptions:
336 if subscription.get('name') is not None:
337 desired_subscriptions.append(module.find_resource_by_name('subscriptions', subscription['name'], params=scope, thin=True))
338 if subscription.get('pool_id') is not None:
339 desired_subscriptions.append(module.find_resource_by_id('subscriptions', subscription['pool_id'], params=scope, thin=True))
340 if subscription.get('upstream_pool_id') is not None:
341 desired_subscriptions.append(
342 module.find_resource_by('subscriptions', 'upstream_pool_id', subscription['upstream_pool_id'], params=scope, thin=True)
343 )
344 desired_subscription_ids = set(item['id'] for item in desired_subscriptions)
345 current_subscriptions = module.list_resource('subscriptions', params=ak_scope) if entity else []
346 current_subscription_ids = set(item['id'] for item in current_subscriptions)
347
348 if desired_subscription_ids != current_subscription_ids:
349 module.record_before('activation_keys/subscriptions', {'id': activation_key['id'], 'subscriptions': current_subscription_ids})
350 module.record_after('activation_keys/subscriptions', {'id': activation_key['id'], 'subscriptions': desired_subscription_ids})
351 module.record_after_full('activation_keys/subscriptions', {'id': activation_key['id'], 'subscriptions': desired_subscription_ids})
352
353 ids_to_remove = current_subscription_ids - desired_subscription_ids
354 if ids_to_remove:
355 payload = {
356 'id': activation_key['id'],
357 'subscriptions': [{'id': item} for item in ids_to_remove],
358 }
359 payload.update(scope)
360 module.resource_action('activation_keys', 'remove_subscriptions', payload)
361
362 ids_to_add = desired_subscription_ids - current_subscription_ids
363 if ids_to_add:
364 payload = {
365 'id': activation_key['id'],
366 'subscriptions': [{'id': item, 'quantity': 1} for item in ids_to_add],
367 }
368 payload.update(scope)
369 module.resource_action('activation_keys', 'add_subscriptions', payload)
370
371 if content_overrides is not None:
372 if entity:
373 product_content = module.resource_action(
374 'activation_keys',
375 'product_content',
376 params={'id': activation_key['id'],
377 'content_access_mode_all': True,
378 'per_page': PER_PAGE},
379 ignore_check_mode=True,
380 )
381 else:
382 product_content = {'results': []}
383 current_content_overrides = {
384 product['content']['label']: product['enabled_content_override']
385 for product in product_content['results']
386 if product['enabled_content_override'] is not None
387 }
388 desired_content_overrides = {
389 product['label']: override_to_boolnone(product['override']) for product in content_overrides
390 }
391 changed_content_overrides = []
392
393 module.record_before('activation_keys/content_overrides', {'id': activation_key['id'], 'content_overrides': current_content_overrides.copy()})
394 module.record_after('activation_keys/content_overrides', {'id': activation_key['id'], 'content_overrides': desired_content_overrides})
395 module.record_after_full('activation_keys/content_overrides', {'id': activation_key['id'], 'content_overrides': desired_content_overrides})
396
397 for label, override in desired_content_overrides.items():
398 if override is not None and override != current_content_overrides.pop(label, None):
399 changed_content_overrides.append({'content_label': label, 'value': override})
400 for label in current_content_overrides.keys():
401 changed_content_overrides.append({'content_label': label, 'remove': True})
402
403 if changed_content_overrides:
404 payload = {
405 'id': activation_key['id'],
406 'content_overrides': changed_content_overrides,
407 }
408 module.resource_action('activation_keys', 'content_override', payload)
409
410 if host_collections is not None:
411 if not entity:
412 current_host_collection_ids = set()
413 elif 'host_collection_ids' in activation_key:
414 current_host_collection_ids = set(activation_key['host_collection_ids'])
415 else:
416 current_host_collection_ids = set(item['id'] for item in activation_key['host_collections'])
417 desired_host_collections = host_collections
418 desired_host_collection_ids = set(item['id'] for item in desired_host_collections)
419
420 if desired_host_collection_ids != current_host_collection_ids:
421 module.record_before('activation_keys/host_collections', {'id': activation_key['id'], 'host_collections': current_host_collection_ids})
422 module.record_after('activation_keys/host_collections', {'id': activation_key['id'], 'host_collections': desired_host_collection_ids})
423 module.record_after_full('activation_keys/host_collections', {'id': activation_key['id'], 'host_collections': desired_host_collection_ids})
424
425 ids_to_remove = current_host_collection_ids - desired_host_collection_ids
426 if ids_to_remove:
427 payload = {
428 'id': activation_key['id'],
429 'host_collection_ids': list(ids_to_remove),
430 }
431 module.resource_action('activation_keys', 'remove_host_collections', payload)
432
433 ids_to_add = desired_host_collection_ids - current_host_collection_ids
434 if ids_to_add:
435 payload = {
436 'id': activation_key['id'],
437 'host_collection_ids': list(ids_to_add),
438 }
439 module.resource_action('activation_keys', 'add_host_collections', payload)
440
441
442 if __name__ == '__main__':
443 main()