Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # (c) 2016, Eric D Helms <[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: content_view
25 version_added: 1.0.0
26 short_description: Manage Content Views
27 description:
28 - Create and manage content views
29 author: "Eric D Helms (@ehelms)"
30 options:
31 name:
32 description:
33 - Name of the Content View
34 required: true
35 type: str
36 description:
37 description:
38 - Description of the Content View
39 type: str
40 label:
41 description:
42 - Label of the Content View. This field cannot be updated.
43 type: str
44 repositories:
45 description:
46 - List of repositories that include name and product.
47 - Cannot be combined with I(composite=True).
48 type: list
49 elements: dict
50 suboptions:
51 name:
52 description:
53 - Name of the Repository to be added
54 type: str
55 required: true
56 product:
57 description:
58 - Product of the Repository to be added
59 type: str
60 required: true
61 auto_publish:
62 description:
63 - Auto publish composite view when a new version of a component content view is created.
64 - Also note auto publish will only happen when the component is marked "latest".
65 default: false
66 type: bool
67 solve_dependencies:
68 description:
69 - Solve RPM dependencies by default on Content View publish
70 type: bool
71 import_only:
72 description:
73 - Designate this Content View for importing from upstream servers only.
74 type: bool
75 version_added: 3.14.0
76 rolling:
77 description:
78 - A rolling content view contains latest synced state of repositories.
79 type: bool
80 version_added: 5.5.0
81 lifecycle_environments:
82 description:
83 - List of lifecycle environments that content of this rolling content view will be promoted to.
84 - Only valid for I(rolling=True).
85 required: False
86 type: list
87 elements: str
88 version_added: 5.9.0
89 composite:
90 description:
91 - A composite view contains other content views.
92 default: false
93 type: bool
94 components:
95 description:
96 - List of content views to includes content_view and either version or latest.
97 - Ignored if I(composite=False).
98 type: list
99 elements: dict
100 suboptions:
101 content_view:
102 description:
103 - Content View name to be added to the Composite Content View
104 type: str
105 required: true
106 latest:
107 description:
108 - Always use the latest Content View Version
109 type: bool
110 default: false
111 content_view_version:
112 description:
113 - Version of the Content View to add
114 type: str
115 aliases:
116 - version
117 extends_documentation_fragment:
118 - theforeman.foreman.foreman
119 - theforeman.foreman.foreman.entity_state_with_defaults
120 - theforeman.foreman.foreman.organization
121 '''
122
123 EXAMPLES = '''
124 - name: "Create or update Fedora content view"
125 theforeman.foreman.content_view:
126 username: "admin"
127 password: "changeme"
128 server_url: "https://foreman.example.com"
129 name: "Fedora CV"
130 organization: "My Cool new Organization"
131 repositories:
132 - name: 'Fedora 26'
133 product: 'Fedora'
134
135 - name: "Create a composite content view"
136 theforeman.foreman.content_view:
137 username: "admin"
138 password: "changeme"
139 server_url: "https://foreman.example.com"
140 name: "Fedora CCV"
141 organization: "My Cool new Organization"
142 composite: true
143 auto_publish: true
144 components:
145 - content_view: Fedora CV
146 content_view_version: 1.0
147 - content_view: Internal CV
148 latest: true
149
150 - name: "Create or update rolling content view"
151 theforeman.foreman.content_view:
152 username: "admin"
153 password: "changeme"
154 server_url: "https://foreman.example.com"
155 name: "Fedora RCV"
156 organization: "My Cool new Organization"
157 rolling: true
158 repositories:
159 - name: 'Fedora 26'
160 product: 'Fedora'
161 '''
162
163 RETURN = '''
164 entity:
165 description: Final state of the affected entities grouped by their type.
166 returned: success
167 type: dict
168 contains:
169 content_views:
170 description: List of content views.
171 type: list
172 elements: dict
173 '''
174
175 import copy
176 from ansible_collections.theforeman.foreman.plugins.module_utils.foreman_helper import KatelloEntityAnsibleModule
177
178
179 cvc_foreman_spec = {
180 'id': {'invisible': True},
181 'content_view': {'type': 'entity', 'required': True},
182 'latest': {'type': 'bool', 'default': False},
183 'content_view_version': {'type': 'entity', 'aliases': ['version']},
184 }
185
186
187 class KatelloContentViewModule(KatelloEntityAnsibleModule):
188 pass
189
190
191 def main():
192 module = KatelloContentViewModule(
193 foreman_spec=dict(
194 name=dict(required=True),
195 description=dict(),
196 label=dict(),
197 composite=dict(type='bool', default=False),
198 rolling=dict(type='bool'),
199 auto_publish=dict(type='bool', default=False),
200 solve_dependencies=dict(type='bool'),
201 import_only=dict(type='bool'),
202 components=dict(type='nested_list', foreman_spec=cvc_foreman_spec, resolve=False),
203 lifecycle_environments=dict(type='entity_list', flat_name='environment_ids'),
204 repositories=dict(type='entity_list', elements='dict', resolve=False, options=dict(
205 name=dict(required=True),
206 product=dict(required=True),
207 )),
208 ),
209 argument_spec=dict(
210 state=dict(default='present', choices=['present_with_defaults', 'present', 'absent']),
211 ),
212 mutually_exclusive=[['repositories', 'components'], ['lifecycle_environments', 'components']],
213 entity_opts=dict(thin=False),
214 )
215
216 # components is None when we're managing a CCV but don't want to adjust its components
217 components = module.foreman_params.pop('components', None)
218 if components:
219 for component in components:
220 if not component['latest'] and component.get('content_view_version') is None:
221 module.fail_json(msg="Content View Component must either have latest=True or provide a Content View Version.")
222
223 with module.api_connection():
224 entity = module.lookup_entity('entity')
225 scope = module.scope_for('organization')
226
227 if not module.desired_absent:
228 if 'repositories' in module.foreman_params:
229 if module.foreman_params['composite']:
230 module.fail_json(msg="Repositories cannot be parts of a Composite Content View.")
231 else:
232 repositories = []
233 for repository in module.foreman_params['repositories']:
234 product = module.find_resource_by_name('products', repository['product'], params=scope, thin=True)
235 repositories.append(module.find_resource_by_name('repositories', repository['name'], params={'product_id': product['id']}, thin=True))
236 module.foreman_params['repositories'] = repositories
237
238 if 'lifecycle_environments' in module.foreman_params:
239 if module.foreman_params['rolling'] is not True:
240 module.fail_json(msg="Lifecycle Environments can only be specified for Rolling Content View.")
241
242 if entity and module.desired_absent:
243 for lce in entity.get('environments', []):
244 module.resource_action('content_views', 'remove_from_environment', {'id': entity['id'], 'environment_id': lce['id']})
245
246 content_view_entity = module.run()
247
248 # only update CVC's of newly created or updated CV's that are composite if components are specified
249 update_dependent_entities = (module.state == 'present' or (module.state == 'present_with_defaults' and module.changed))
250 if update_dependent_entities and content_view_entity['composite'] and components is not None:
251 if not module.changed:
252 content_view_entity['content_view_components'] = entity['content_view_components']
253 current_cvcs = content_view_entity.get('content_view_components', [])
254
255 # only record a subset of data
256 current_cvcs_record = []
257 for cvc in current_cvcs:
258 entry = {"id": cvc['id'], "content_view_id": cvc['content_view']['id'], "latest": cvc['latest']}
259 if 'content_view_version' in cvc and isinstance(cvc['content_view_version'], dict):
260 entry['content_view_version_id'] = cvc['content_view_version'].get('id')
261 current_cvcs_record.append(entry)
262 module.record_before('content_views/components', {'composite_content_view_id': content_view_entity['id'],
263 'content_view_components': current_cvcs_record})
264 final_cvcs_record = copy.deepcopy(current_cvcs_record)
265
266 components_to_add = []
267 ccv_scope = {'composite_content_view_id': content_view_entity['id']}
268 for component in components:
269 cvc = {
270 'content_view': module.find_resource_by_name('content_views', name=component['content_view'], params=scope),
271 'latest': component['latest'],
272 }
273 cvc_matched = next((item for item in current_cvcs if item['content_view']['id'] == cvc['content_view']['id']), None)
274 if not cvc['latest']:
275 search = "content_view_id={0},version={1}".format(cvc['content_view']['id'], component['content_view_version'])
276 cvc['content_view_version'] = module.find_resource('content_view_versions', search=search, thin=True)
277 cvc['latest'] = False
278 if cvc_matched and cvc_matched['latest']:
279 # When changing to latest=False & version is the latest we must send 'content_view_version' to the server
280 # Let's fake, it wasn't there...
281 cvc_matched.pop('content_view_version', None)
282 cvc_matched.pop('content_view_version_id', None)
283 if cvc_matched:
284 module.ensure_entity(
285 'content_view_components', cvc, cvc_matched, state='present', foreman_spec=cvc_foreman_spec, params=ccv_scope)
286 current_cvcs.remove(cvc_matched)
287 else:
288 cvc['content_view_id'] = cvc.pop('content_view')['id']
289 if 'content_view_version' in cvc:
290 cvc['content_view_version_id'] = cvc.pop('content_view_version')['id']
291 components_to_add.append(cvc)
292
293 if components_to_add:
294 payload = {
295 'composite_content_view_id': content_view_entity['id'],
296 'components': components_to_add,
297 }
298 module.resource_action('content_view_components', 'add_components', payload)
299
300 final_cvcs_record.extend(components_to_add)
301
302 # desired cvcs have already been updated and removed from `current_cvcs`
303 components_to_remove = [item['id'] for item in current_cvcs]
304 if components_to_remove:
305 payload = {
306 'composite_content_view_id': content_view_entity['id'],
307 'component_ids': components_to_remove,
308 }
309 module.resource_action('content_view_components', 'remove_components', payload)
310
311 # some entries in "final" don't have an id yet, as it is only assigned on creation of a cv component,
312 # which didn't happen yet when we record the data
313 final_cvcs_record = [item for item in final_cvcs_record if item.get('id', 'NEW_ID') not in components_to_remove]
314
315 module.record_after('content_views/components', {'composite_content_view_id': content_view_entity['id'],
316 'content_view_components': final_cvcs_record})
317 module.record_after_full('content_views/components', {'composite_content_view_id': content_view_entity['id'],
318 'content_view_components': final_cvcs_record})
319
320
321 if __name__ == '__main__':
322 main()