Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/content_subscribedlibrary.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: content_subscribedlibrary
12 short_description: Creates a new subscribed library
13 description: 'Creates a new subscribed library. '
14 deprecated:
15 removed_in: 5.0.0
16 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
17 alternative: Use M(vmware.vmware.subscribed_content_library) instead.
18 options:
19 client_token:
20 description:
21 - 'Unique token generated on the client for each creation request. The token
22 should be a universally unique identifier (UUID), for example: b8a2a2e3-2314-43cd-a871-6ede0f429751.
23 This token can be used to guarantee idempotent creation.'
24 - If not specified creation is not idempotent.
25 type: str
26 creation_time:
27 description:
28 - The date and time when this library was created.
29 - This field is not used for the create operation. It will always be present
30 in the result of the get or list operations. It is not used for the update
31 operation.
32 type: str
33 description:
34 description:
35 - A human-readable description for this library.
36 - This field is optional for the create operation. Leaving it unset during
37 creation will result in an empty string value. It will always be present
38 in the result of a get or list operation. It is optional for the update
39 operation. Leaving it unset during update indicates that the description
40 should be left unchanged.
41 type: str
42 id:
43 description:
44 - An identifier which uniquely identifies this LibraryModel.
45 - This field is not used for the create operation. It will not be present
46 in the result of the get or list operations. It is not used for the update
47 operation.
48 - 'When clients pass a value of this structure as a parameter, the field must
49 be the id of a resource returned by M(vmware.vmware_rest.content_library_info). '
50 type: str
51 last_modified_time:
52 description:
53 - 'The date and time when this library was last updated. '
54 - ' This field is updated automatically when the library properties are changed.
55 This field is not affected by adding, removing, or modifying a library
56 item or its content within the library. Tagging the library or syncing
57 the subscribed library does not alter this field.'
58 - ''
59 - This field is not used for the create operation. It will always be present
60 in the result of the get or list operations. It is not used for the update
61 operation.
62 type: str
63 last_sync_time:
64 description:
65 - 'The date and time when this library was last synchronized. '
66 - ' This field applies only to subscribed libraries. It is updated every time
67 a synchronization is triggered on the library. The value is unset for
68 a local library.'
69 - ''
70 - This field is not used for the create operation. It is optional in the result
71 of the get or list operations. It is not used for the update operation.
72 type: str
73 library_id:
74 description:
75 - Identifier of the subscribed library whose content should be evicted.
76 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.content_library_info).
77 Required with I(state=['absent', 'evict', 'present', 'sync'])
78 type: str
79 name:
80 description:
81 - 'The name of the library. '
82 - ' A Library is identified by a human-readable name. Library names cannot
83 be undefined or an empty string. Names do not have to be unique.'
84 - ''
85 - This field must be provided for the create operation. It will always be
86 present in the result of the get or list operations. It is optional for
87 the update operation.
88 type: str
89 optimization_info:
90 description:
91 - Defines various optimizations and optimization parameters applied to this
92 library.
93 - This field is optional for the create operation. It is optional in the result
94 of the get or list operations. It is optional for the update operation.
95 - 'Valid attributes are:'
96 - ' - C(optimize_remote_publishing) (bool): If set to true then library would
97 be optimized for remote publishing. '
98 - ' Turn it on if remote publishing is dominant use case for this library.
99 Remote publishing means here that publisher and subscribers are not the
100 part of the same Vcenter SSO domain. '
101 - ''
102 - ' Any optimizations could be done as result of turning on this optimization
103 during library creation. For example, library content could be stored
104 in different format but optimizations are not limited to just storage
105 format. '
106 - ''
107 - ' Note, that value of this toggle could be set only during creation of the
108 library and you would need to migrate your library in case you need to
109 change this value (optimize the library for different use case).'
110 - ''
111 - This field is optional for the create operation. If not specified for the
112 create, the default is for the library to not be optmized for specific
113 use case. It is not used for the update operation. (['present'])
114 type: dict
115 publish_info:
116 description:
117 - 'Defines how this library is published so that it can be subscribed to by
118 a remote subscribed library. '
119 - ' The PublishInfo defines where and how the metadata for this local library
120 is accessible. A local library is only published publically if PublishInfo.published
121 is true.'
122 - ''
123 - This field is optional for the create and update operations. If not specified
124 during creation, the default is for the library to not be published. If
125 not specified during update, the field is left unchanged.
126 - 'Valid attributes are:'
127 - ' - C(authentication_method) (str): This option indicates how a subscribed
128 library should authenticate to the published library endpoint. ([''present''])'
129 - ' - Accepted values:'
130 - ' - BASIC'
131 - ' - NONE'
132 - ' - C(published) (bool): Whether the local library is published.'
133 - This field is required for the LocalLibrary.create operation. It is optional
134 for the LocalLibrary.update operation, and if unset the value will not
135 be changed. When the existing authentication method is BASIC and the local
136 library is published, the PublishInfo.current-password field is required
137 before turning off publishing. This field will always be present in the
138 results of the LocalLibrary.get operation. (['present'])
139 - ' - C(publish_url) (str): The URL to which the library metadata is published
140 by the Content Library Service. '
141 - ' This value can be used to set the SubscriptionInfo.subscription-url property
142 when creating a subscribed library.'
143 - ''
144 - This field is not used for the create operation. It will always be present
145 in the result of the get or list operations. It is not used for the update
146 operation. (['present'])
147 - ' - C(user_name) (str): The username to require for authentication.'
148 - This field is optional for the LocalLibrary.create and LocalLibrary.update
149 operations. When the authentication method is NONE, the username can be
150 left unset. When the authentication method is BASIC, the username is ignored
151 in the current release. It defaults to "vcsp". It is preferable to leave
152 this unset. If specified, it must be set to "vcsp". (['present'])
153 - ' - C(password) (str): The new password to require for authentication.'
154 - This field is optional for the LocalLibrary.create operation. When the authentication
155 method is NONE, the password can be left unset. When the authentication
156 method is BASIC, the password should be a non-empty string. This field
157 is optional for the LocalLibrary.update operation. Leaving it unset during
158 update indicates that the password is not changed. When the password is
159 changed, the PublishInfo.current-password field is required. This field
160 is not used for the LocalLibrary.get operation. (['present'])
161 - ' - C(current_password) (str): The current password to verify. This field
162 is available starting in vSphere 6.7.'
163 - This field is unused for the LocalLibrary.create operation. This field is
164 optional for the LocalLibrary.update operation. When the existing authentication
165 method is NONE, the current password can be left unset. When the existing
166 authentication method is BASIC, the current password is verified before
167 applying the new PublishInfo.password, turning off authentication, or
168 unpublishing the library. This field is not used for the LocalLibrary.get
169 operation. (['present'])
170 - ' - C(persist_json_enabled) (bool): Whether library and library item metadata
171 are persisted in the storage backing as JSON files. This flag only applies
172 if the local library is published. '
173 - ' Enabling JSON persistence allows you to synchronize a subscribed library
174 manually instead of over HTTP. You copy the local library content and
175 metadata to another storage backing manually and then create a subscribed
176 library referencing the location of the library JSON file in the SubscriptionInfo.subscription-url.
177 When the subscribed library''s storage backing matches the subscription
178 URL, files do not need to be copied to the subscribed library. '
179 - ''
180 - ' For a library backed by a datastore, the library JSON file will be stored
181 at the path contentlib-{library_id}/lib.json on the datastore. '
182 - ''
183 - ' For a library backed by a remote file system, the library JSON file will
184 be stored at {library_id}/lib.json in the remote file system path.'
185 - ''
186 - This field is optional for the create operation. It will always be present
187 in the result of the get or list operations. It is optional for the update
188 operation. (['present'])
189 type: dict
190 security_policy_id:
191 description:
192 - 'Represents the security policy applied to this library. '
193 - ' Setting the field will make the library secure. This field is ignored
194 in update operation if LibraryModel.unset-security-policy-id is set to
195 true.'
196 - ''
197 - This field is optional for the create and update operations. If not set
198 in create operation, the library will be insecure. If not specified in
199 update operation, the field is left unchanged.
200 - 'When clients pass a value of this structure as a parameter, the field must
201 be the id of a resource returned by M(vmware.vmware_rest.content_library_info). '
202 type: str
203 server_guid:
204 description:
205 - The unique identifier of the vCenter server where the library exists.
206 - This field is optional for the create operation. It will always be present
207 in the result of the get or list operations. It is not used for the update
208 operation.
209 - 'When clients pass a value of this structure as a parameter, the field must
210 be the id of a resource returned by M(vmware.vmware_rest.vcenter_cluster_info). '
211 type: str
212 session_timeout:
213 description:
214 - 'Timeout settings for client session. '
215 - 'The maximal number of seconds for the whole operation including connection
216 establishment, request sending and response. '
217 - The default value is 300s.
218 type: float
219 version_added: 2.1.0
220 state:
221 choices:
222 - absent
223 - evict
224 - present
225 - probe
226 - sync
227 default: present
228 description: []
229 type: str
230 storage_backings:
231 description:
232 - 'The list of default storage backings which are available for this library. '
233 - ' A StorageBacking defines a default storage location which can be used
234 to store files for library items in this library. Some library items,
235 for instance, virtual machine template items, support files that may be
236 distributed across various storage backings. One or more item files may
237 or may not be located on the default storage backing. '
238 - ''
239 - ' Multiple default storage locations are not currently supported but may
240 become supported in future releases.'
241 - ''
242 - This field must be provided for the create operation. It will always be
243 present in the result of the get or list operations. It is not used for
244 the update operation.
245 - 'Valid attributes are:'
246 - ' - C(type) (str): This option specifies the type of the StorageBacking.
247 ([''present''])'
248 - ' - Accepted values:'
249 - ' - DATASTORE'
250 - ' - OTHER'
251 - ' - C(datastore_id) (str): Identifier of the datastore used to store the
252 content in the library.'
253 - This field is optional and it is only relevant when the value of StorageBacking.type
254 is DATASTORE.
255 - When clients pass a value of this structure as a parameter, the field must
256 be the id of a resource returned by M(vmware.vmware_rest.vcenter_datastore_info).
257 (['present'])
258 - ' - C(storage_uri) (str): URI identifying the location used to store the
259 content in the library. '
260 - ' The following URI formats are supported: '
261 - ''
262 - ' vSphere 6.5 '
263 - ''
264 - ' - nfs://server/path?version=4 (for vCenter Server Appliance only) -
265 Specifies an NFS Version 4 server.'
266 - ' - nfs://server/path (for vCenter Server Appliance only) - Specifies
267 an NFS Version 3 server. The nfs://server:/path format is also supported.'
268 - ' - smb://server/path - Specifies an SMB server or Windows share.'
269 - ' '
270 - ' vSphere 6.0 Update 1 '
271 - ''
272 - ' - nfs://server:/path (for vCenter Server Appliance only)'
273 - ' - file://unc-server/path (for vCenter Server for Windows only)'
274 - ' - file:///mount/point (for vCenter Server Appliance only) - Local file
275 URIs are supported only when the path is a local mount point for an NFS
276 file system. Use of file URIs is strongly discouraged. Instead, use an
277 NFS URI to specify the remote file system.'
278 - ' '
279 - ' vSphere 6.0 '
280 - ''
281 - ' - nfs://server:/path (for vCenter Server Appliance only)'
282 - ' - file://unc-server/path (for vCenter Server for Windows only)'
283 - ' - file:///path - Local file URIs are supported but strongly discouraged
284 because it may interfere with the performance of vCenter Server.'
285 - ' '
286 - This field is optional and it is only relevant when the value of StorageBacking.type
287 is OTHER. (['present'])
288 elements: dict
289 type: list
290 subscription_info:
291 description:
292 - 'Defines the subscription behavior for this Library. '
293 - ' The SubscriptionInfo defines how this subscribed library synchronizes
294 to a remote source. Setting the value will determine the remote source
295 to which the library synchronizes, and how. Changing the subscription
296 will result in synchronizing to a new source. If the new source differs
297 from the old one, the old library items and data will be lost. Setting
298 SubscriptionInfo.automatic-sync-enabled to false will halt subscription
299 but will not remove existing cached data.'
300 - ''
301 - This field is optional for the create and update operations. If not specified
302 during creation, a default will be created without an active subscription.
303 If not specified during update, the field is left unchanged.
304 - 'Valid attributes are:'
305 - ' - C(authentication_method) (str): Indicate how the subscribed library
306 should authenticate with the published library endpoint. ([''present'',
307 ''probe''])'
308 - ' - Accepted values:'
309 - ' - BASIC'
310 - ' - NONE'
311 - ' - C(automatic_sync_enabled) (bool): Whether the library should participate
312 in automatic library synchronization. In order for automatic synchronization
313 to happen, the global ConfigurationModel.automatic-sync-enabled option
314 must also be true. The subscription is still active even when automatic
315 synchronization is turned off, but synchronization is only activated with
316 an explicit call to SubscribedLibrary.sync or SubscribedItem.sync. In
317 other words, manual synchronization is still available even when automatic
318 synchronization is disabled.'
319 - This field must be provided for the create operation. It will always be
320 present in the result of the get or list operations. It is optional for
321 the update operation. (['present', 'probe'])
322 - ' - C(on_demand) (bool): Indicates whether a library item''s content will
323 be synchronized only on demand. '
324 - ' If this is set to true, then the library item''s metadata will be synchronized
325 but the item''s content (its files) will not be synchronized. The Content
326 Library Service will synchronize the content upon request only. This can
327 cause the first use of the content to have a noticeable delay. '
328 - ''
329 - ' Items without synchronized content can be forcefully synchronized in advance
330 using the SubscribedItem.sync call with forceSyncContent set to true.
331 Once content has been synchronized, the content can removed with the SubscribedItem.evict
332 call. '
333 - ''
334 - ' If this value is set to false, all content will be synchronized in advance.'
335 - ''
336 - This field must be provided for the create operation. It will always be
337 present in the result of the get or list operations. It is optional for
338 the update operation. (['present', 'probe'])
339 - ' - C(password) (str): The password to use when authenticating. '
340 - ' The password must be set when using a password-based authentication method;
341 empty strings are not allowed.'
342 - ''
343 - This field is optional for the create operation. It will not be present
344 in the result of the get or list operations. It is optional for the update
345 operation. (['present', 'probe'])
346 - ' - C(ssl_thumbprint) (str): An optional SHA-1 hash of the SSL certificate
347 for the remote endpoint. '
348 - ' If this value is defined the SSL certificate will be verified by comparing
349 it to the SSL thumbprint. The SSL certificate must verify against the
350 thumbprint. When specified, the standard certificate chain validation
351 behavior is not used. The certificate chain is validated normally if this
352 value is unset. The specified sslThumbprint will not be checked for SSL
353 certificate validation if {SubscriptionInfo#sslCertificate} is also set.'
354 - ''
355 - This field is optional for the create operation. It will not be present
356 in the result of the get or list operations. It is optional for the update
357 operation. (['present', 'probe'])
358 - ' - C(subscription_url) (str): The URL of the endpoint where the metadata
359 for the remotely published library is being served. '
360 - ' This URL can be the PublishInfo.publish-url of the published library (for
361 example, https://server/path/lib.json). '
362 - ''
363 - ' If the source content comes from a published library with PublishInfo.persist-json-enabled,
364 the subscription URL can be a URL pointing to the library JSON file on
365 a datastore or remote file system. The supported formats are: '
366 - ''
367 - ' vSphere 6.5 '
368 - ''
369 - ' - ds:///vmfs/volumes/{uuid}/mylibrary/lib.json (for datastore)'
370 - ' - nfs://server/path/mylibrary/lib.json (for NFSv3 server on vCenter
371 Server Appliance)'
372 - ' - nfs://server/path/mylibrary/lib.json?version=4 (for NFSv4 server on
373 vCenter Server Appliance) '
374 - ' - smb://server/path/mylibrary/lib.json (for SMB server)'
375 - ' '
376 - ' vSphere 6.0 '
377 - ''
378 - ' - file://server/mylibrary/lib.json (for UNC server on vCenter Server
379 for Windows)'
380 - ' - file:///path/mylibrary/lib.json (for local file system)'
381 - ' '
382 - ' When you specify a DS subscription URL, the datastore must be on the same
383 vCenter Server as the subscribed library. When you specify an NFS or SMB
384 subscription URL, the StorageBacking.storage-uri of the subscribed library
385 must be on the same remote file server and should share a common parent
386 path with the subscription URL.'
387 - ''
388 - This field must be provided for the create operation. It will always be
389 present in the result of the get or list operations. It is optional for
390 the update operation. (['present', 'probe'])
391 - ' - C(user_name) (str): The username to use when authenticating. '
392 - ' The username must be set when using a password-based authentication method.
393 Empty strings are allowed for usernames.'
394 - ''
395 - This field is optional for the create operation. It is optional in the result
396 of the get or list operations. It is optional for the update operation.
397 (['present', 'probe'])
398 - ' - C(source_info) (dict): Information about the source published library.
399 This field will be set for a subscribed library which is associated with
400 a subscription of the published library.'
401 - This field is optional for the create operation. It is optional in the result
402 of the get or list operations. It is optional for the update operation.
403 (['present', 'probe'])
404 - ' - Accepted keys:'
405 - ' - source_library (string): Identifier of the published library.'
406 - This field must be provided for the create operation. It will always be
407 present in the result of the get or list operations. It is optional for
408 the update operation.
409 - 'When clients pass a value of this structure as a parameter, the field must
410 be the id of a resource returned by M(vmware.vmware_rest.content_library_info). '
411 - ' - subscription (string): Identifier of the subscription associated
412 with the subscribed library.'
413 - This field must be provided for the create operation. It will always be
414 present in the result of the get or list operations. It is optional for
415 the update operation.
416 - 'When clients pass a value of this structure as a parameter, the field must
417 be the id of a resource returned by M(vmware.vmware_rest.content_library_subscriptions_info). '
418 type: dict
419 type:
420 choices:
421 - LOCAL
422 - SUBSCRIBED
423 description:
424 - 'The I(library_type) enumerated type defines the type of a LibraryModel. '
425 - ' The type of a library can be used to determine which additional services
426 can be performed with a library.'
427 type: str
428 unset_security_policy_id:
429 description:
430 - 'This represents the intent of the change to LibraryModel.security-policy-id
431 in update operation. '
432 - ' If this field is set to true, any security policy applied to the library
433 will be removed. If this field is set to false, any security policy applied
434 to library will be changed to the value specified in LibraryModel.security-policy-id,
435 if any.'
436 - ''
437 - This field is optional for the update operation. If unset, any existing
438 security policy will be changed to the value specified in LibraryModel.security-policy-id,
439 if any.
440 type: bool
441 vcenter_hostname:
442 description:
443 - The hostname or IP address of the vSphere vCenter
444 - If the value is not specified in the task, the value of environment variable
445 C(VMWARE_HOST) will be used instead.
446 required: true
447 type: str
448 vcenter_password:
449 description:
450 - The vSphere vCenter password
451 - If the value is not specified in the task, the value of environment variable
452 C(VMWARE_PASSWORD) will be used instead.
453 required: true
454 type: str
455 vcenter_rest_log_file:
456 description:
457 - 'You can use this optional parameter to set the location of a log file. '
458 - 'This file will be used to record the HTTP REST interaction. '
459 - 'The file will be stored on the host that runs the module. '
460 - 'If the value is not specified in the task, the value of '
461 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
462 type: str
463 vcenter_username:
464 description:
465 - The vSphere vCenter username
466 - If the value is not specified in the task, the value of environment variable
467 C(VMWARE_USER) will be used instead.
468 required: true
469 type: str
470 vcenter_validate_certs:
471 default: true
472 description:
473 - Allows connection when SSL certificates are not valid. Set to C(false) when
474 certificates are not trusted.
475 - If the value is not specified in the task, the value of environment variable
476 C(VMWARE_VALIDATE_CERTS) will be used instead.
477 type: bool
478 version:
479 description:
480 - 'A version number which is updated on metadata changes. This value allows
481 clients to detect concurrent updates and prevent accidental clobbering
482 of data. '
483 - ' This value represents a number which is incremented every time library
484 properties, such as name or description, are changed. It is not incremented
485 by changes to a library item within the library, including adding or removing
486 items. It is also not affected by tagging the library.'
487 - ''
488 - This field is not used for the create operation. It will always be present
489 in the result of a get or list operation. It is optional for the update
490 operation. Leaving it unset during update indicates that you do not need
491 to detect concurrent updates.
492 type: str
493 author:
494 - Ansible Cloud Team (@ansible-collections)
495 version_added: 2.0.0
496 requirements:
497 - vSphere 7.0.3 or greater
498 - python >= 3.6
499 - aiohttp
500 notes:
501 - Tested on vSphere 7.0.3
502 """
503
504 EXAMPLES = r"""
505 - name: Create a content library pointing on a NFS share
506 vmware.vmware_rest.content_locallibrary:
507 name: my_library_on_nfs
508 description: automated
509 publish_info:
510 published: true
511 authentication_method: NONE
512 storage_backings:
513 - storage_uri: nfs://datastore.test/srv/share/content-library
514 type: OTHER
515 state: present
516 register: nfs_lib
517
518 - name: Create subscribed library
519 vmware.vmware_rest.content_subscribedlibrary:
520 name: sub_lib
521 subscription_info:
522 subscription_url: '{{ nfs_lib.value.publish_info.publish_url }}'
523 authentication_method: NONE
524 automatic_sync_enabled: false
525 on_demand: true
526 storage_backings:
527 - datastore_id: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/rw_datastore') }}"
528 type: DATASTORE
529 register: sub_lib
530
531 - name: Create subscribed library (again)
532 vmware.vmware_rest.content_subscribedlibrary:
533 name: sub_lib
534 subscription_info:
535 subscription_url: '{{ nfs_lib.value.publish_info.publish_url }}'
536 authentication_method: NONE
537 automatic_sync_enabled: false
538 on_demand: true
539 storage_backings:
540 - datastore_id: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/rw_datastore') }}"
541 type: DATASTORE
542 register: result
543
544 - name: Clean up the cache
545 vmware.vmware_rest.content_subscribedlibrary:
546 name: sub_lib
547 library_id: '{{ sub_lib.id }}'
548 state: evict
549
550 - name: Trigger a library sync
551 vmware.vmware_rest.content_subscribedlibrary:
552 name: sub_lib
553 library_id: '{{ sub_lib.id }}'
554 state: sync
555 """
556 RETURN = r"""
557 # content generated by the update_return_section callback# task: Delete all the subscribed libraries
558 msg:
559 description: Delete all the subscribed libraries
560 returned: On success
561 sample: All items completed
562 type: str
563 results:
564 description: Delete all the subscribed libraries
565 returned: On success
566 sample:
567 - _ansible_item_label:
568 creation_time: '2022-11-23T20:06:05.189Z'
569 description: ''
570 id: 8b4e355e-a463-44f1-9b04-d0786a49cc7d
571 last_modified_time: '2022-11-23T20:06:05.189Z'
572 last_sync_time: '2022-11-23T20:06:07.717Z'
573 name: sub_lib
574 server_guid: 52fb0b5e-ffc3-465b-bf4f-e4e6d5423cf5
575 storage_backings:
576 - datastore_id: datastore-1065
577 type: DATASTORE
578 subscription_info:
579 authentication_method: NONE
580 automatic_sync_enabled: 0
581 on_demand: 1
582 subscription_url: https://vcenter.test:443/cls/vcsp/lib/a66d5c73-57f8-4a3a-9361-292a55f68516/lib.json
583 type: SUBSCRIBED
584 version: '4'
585 _ansible_no_log: null
586 ansible_loop_var: item
587 changed: 1
588 failed: 0
589 invocation:
590 module_args:
591 client_token: null
592 creation_time: null
593 description: null
594 id: null
595 last_modified_time: null
596 last_sync_time: null
597 library_id: 8b4e355e-a463-44f1-9b04-d0786a49cc7d
598 name: null
599 optimization_info: null
600 publish_info: null
601 server_guid: null
602 session_timeout: null
603 state: absent
604 storage_backings: null
605 subscription_info: null
606 type: null
607 vcenter_hostname: vcenter.test
608 vcenter_password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
609 vcenter_rest_log_file: /tmp/vmware_rest.log
610 vcenter_username: [email protected]
611 vcenter_validate_certs: 0
612 version: null
613 item:
614 creation_time: '2022-11-23T20:06:05.189Z'
615 description: ''
616 id: 8b4e355e-a463-44f1-9b04-d0786a49cc7d
617 last_modified_time: '2022-11-23T20:06:05.189Z'
618 last_sync_time: '2022-11-23T20:06:07.717Z'
619 name: sub_lib
620 server_guid: 52fb0b5e-ffc3-465b-bf4f-e4e6d5423cf5
621 storage_backings:
622 - datastore_id: datastore-1065
623 type: DATASTORE
624 subscription_info:
625 authentication_method: NONE
626 automatic_sync_enabled: 0
627 on_demand: 1
628 subscription_url: https://vcenter.test:443/cls/vcsp/lib/a66d5c73-57f8-4a3a-9361-292a55f68516/lib.json
629 type: SUBSCRIBED
630 version: '4'
631 value: {}
632 type: list
633 """
634
635
636 # This structure describes the format of the data expected by the end-points
637 PAYLOAD_FORMAT = {
638 "create": {
639 "query": {"client_token": "client_token"},
640 "body": {
641 "creation_time": "creation_time",
642 "description": "description",
643 "id": "id",
644 "last_modified_time": "last_modified_time",
645 "last_sync_time": "last_sync_time",
646 "name": "name",
647 "optimization_info": "optimization_info",
648 "publish_info": "publish_info",
649 "security_policy_id": "security_policy_id",
650 "server_guid": "server_guid",
651 "storage_backings": "storage_backings",
652 "subscription_info": "subscription_info",
653 "type": "type",
654 "unset_security_policy_id": "unset_security_policy_id",
655 "version": "version",
656 },
657 "path": {},
658 },
659 "delete": {"query": {}, "body": {}, "path": {"library_id": "library_id"}},
660 "sync": {"query": {}, "body": {}, "path": {"library_id": "library_id"}},
661 "update": {
662 "query": {},
663 "body": {
664 "creation_time": "creation_time",
665 "description": "description",
666 "id": "id",
667 "last_modified_time": "last_modified_time",
668 "last_sync_time": "last_sync_time",
669 "name": "name",
670 "optimization_info": "optimization_info",
671 "publish_info": "publish_info",
672 "security_policy_id": "security_policy_id",
673 "server_guid": "server_guid",
674 "storage_backings": "storage_backings",
675 "subscription_info": "subscription_info",
676 "type": "type",
677 "unset_security_policy_id": "unset_security_policy_id",
678 "version": "version",
679 },
680 "path": {"library_id": "library_id"},
681 },
682 "probe": {
683 "query": {},
684 "body": {"subscription_info": "subscription_info"},
685 "path": {},
686 },
687 "evict": {"query": {}, "body": {}, "path": {"library_id": "library_id"}},
688 } # pylint: disable=line-too-long
689
690 from ansible.module_utils.basic import env_fallback
691 import os
692
693 if os.getenv("VMWARE_ENABLE_TURBO", False):
694 try:
695 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
696 AnsibleTurboModule as AnsibleModule,
697 )
698
699 AnsibleModule.collection_name = "vmware.vmware_rest"
700 except ImportError:
701 from ansible.module_utils.basic import AnsibleModule
702 else:
703 from ansible.module_utils.basic import AnsibleModule
704
705 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
706 exists,
707 gen_args,
708 get_device_info,
709 get_subdevice_type,
710 open_session,
711 prepare_payload,
712 session_timeout,
713 update_changed_flag,
714 )
715
716
717 def prepare_argument_spec():
718 argument_spec = {
719 "vcenter_hostname": dict(
720 type="str",
721 required=True,
722 fallback=(env_fallback, ["VMWARE_HOST"]),
723 ),
724 "vcenter_username": dict(
725 type="str",
726 required=True,
727 fallback=(env_fallback, ["VMWARE_USER"]),
728 ),
729 "vcenter_password": dict(
730 type="str",
731 required=True,
732 no_log=True,
733 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
734 ),
735 "vcenter_validate_certs": dict(
736 type="bool",
737 required=False,
738 default=True,
739 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
740 ),
741 "vcenter_rest_log_file": dict(
742 type="str",
743 required=False,
744 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
745 ),
746 "session_timeout": dict(
747 type="float",
748 required=False,
749 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
750 ),
751 }
752
753 argument_spec["client_token"] = {"no_log": True, "type": "str"}
754 argument_spec["creation_time"] = {"type": "str"}
755 argument_spec["description"] = {"type": "str"}
756 argument_spec["id"] = {"type": "str"}
757 argument_spec["last_modified_time"] = {"type": "str"}
758 argument_spec["last_sync_time"] = {"type": "str"}
759 argument_spec["library_id"] = {"type": "str"}
760 argument_spec["name"] = {"type": "str"}
761 argument_spec["optimization_info"] = {"type": "dict"}
762 argument_spec["publish_info"] = {"type": "dict"}
763 argument_spec["security_policy_id"] = {"type": "str"}
764 argument_spec["server_guid"] = {"type": "str"}
765 argument_spec["state"] = {
766 "type": "str",
767 "choices": ["absent", "evict", "present", "probe", "sync"],
768 "default": "present",
769 }
770 argument_spec["storage_backings"] = {"type": "list", "elements": "dict"}
771 argument_spec["subscription_info"] = {"type": "dict"}
772 argument_spec["type"] = {"type": "str", "choices": ["LOCAL", "SUBSCRIBED"]}
773 argument_spec["unset_security_policy_id"] = {"type": "bool"}
774 argument_spec["version"] = {"type": "str"}
775
776 return argument_spec
777
778
779 async def main():
780 required_if = list([])
781
782 module_args = prepare_argument_spec()
783 module = AnsibleModule(
784 argument_spec=module_args, required_if=required_if, supports_check_mode=False
785 )
786 if not module.params["vcenter_hostname"]:
787 module.fail_json("vcenter_hostname cannot be empty")
788 if not module.params["vcenter_username"]:
789 module.fail_json("vcenter_username cannot be empty")
790 if not module.params["vcenter_password"]:
791 module.fail_json("vcenter_password cannot be empty")
792 try:
793 session = await open_session(
794 vcenter_hostname=module.params["vcenter_hostname"],
795 vcenter_username=module.params["vcenter_username"],
796 vcenter_password=module.params["vcenter_password"],
797 validate_certs=module.params["vcenter_validate_certs"],
798 log_file=module.params["vcenter_rest_log_file"],
799 )
800 except Exception as err:
801 if hasattr(err, "get_message"):
802 module.fail_json(err.get_message())
803 else:
804 module.fail_json(str(err))
805 result = await entry_point(module, session)
806 module.exit_json(**result)
807
808
809 # template: default_module.j2
810 def build_url(params):
811 return ("https://{vcenter_hostname}" "/api/content/subscribed-library").format(
812 **params
813 )
814
815
816 async def entry_point(module, session):
817
818 if module.params["state"] == "present":
819 if "_create" in globals():
820 operation = "create"
821 else:
822 operation = "update"
823 elif module.params["state"] == "absent":
824 operation = "delete"
825 else:
826 operation = module.params["state"]
827
828 func = globals()["_" + operation]
829
830 return await func(module.params, session)
831
832
833 async def _create(params, session):
834
835 lookup_url = per_id_url = build_url(params)
836 uniquity_keys = ["name"]
837 comp_func = None
838
839 _json = None
840
841 if params["library_id"]:
842 _json = await get_device_info(session, build_url(params), params["library_id"])
843
844 if not _json and (uniquity_keys or comp_func):
845 _json = await exists(
846 params,
847 session,
848 url=lookup_url,
849 uniquity_keys=uniquity_keys,
850 per_id_url=per_id_url,
851 comp_func=comp_func,
852 )
853
854 if _json:
855 if "value" not in _json: # 7.0.2+
856 _json = {"value": _json}
857 if "_update" in globals():
858 params["library_id"] = _json["id"]
859 return await globals()["_update"](params, session)
860
861 return await update_changed_flag(_json, 200, "get")
862
863 payload = prepare_payload(params, PAYLOAD_FORMAT["create"])
864 _url = ("https://{vcenter_hostname}" "/api/content/subscribed-library").format(
865 **params
866 )
867 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
868 if resp.status == 500:
869 text = await resp.text()
870 raise Exception(f"Request has failed: status={resp.status}, {text}")
871 try:
872 if resp.headers["Content-Type"] == "application/json":
873 _json = await resp.json()
874 except KeyError:
875 _json = {}
876
877 if (resp.status in [200, 201]) and "error" not in _json:
878 if isinstance(_json, str): # 7.0.2 and greater
879 _id = _json # TODO: fetch the object
880 elif isinstance(_json, dict) and "value" not in _json:
881 _id = list(_json["value"].values())[0]
882 elif isinstance(_json, dict) and "value" in _json:
883 _id = _json["value"]
884 _json_device_info = await get_device_info(session, _url, _id)
885 if _json_device_info:
886 _json = _json_device_info
887
888 return await update_changed_flag(_json, resp.status, "create")
889
890
891 async def _delete(params, session):
892 _in_query_parameters = PAYLOAD_FORMAT["delete"]["query"].keys()
893 payload = prepare_payload(params, PAYLOAD_FORMAT["delete"])
894 subdevice_type = get_subdevice_type("/api/content/subscribed-library/{library_id}")
895 if subdevice_type and not params[subdevice_type]:
896 _json = await exists(params, session, build_url(params))
897 if _json:
898 params[subdevice_type] = _json["id"]
899 _url = (
900 "https://{vcenter_hostname}" "/api/content/subscribed-library/{library_id}"
901 ).format(**params) + gen_args(params, _in_query_parameters)
902 async with session.delete(_url, json=payload, **session_timeout(params)) as resp:
903 try:
904 if resp.headers["Content-Type"] == "application/json":
905 _json = await resp.json()
906 except KeyError:
907 _json = {}
908 return await update_changed_flag(_json, resp.status, "delete")
909
910
911 async def _evict(params, session):
912 _in_query_parameters = PAYLOAD_FORMAT["evict"]["query"].keys()
913 payload = prepare_payload(params, PAYLOAD_FORMAT["evict"])
914 subdevice_type = get_subdevice_type(
915 "/api/content/subscribed-library/{library_id}?action=evict"
916 )
917 if subdevice_type and not params[subdevice_type]:
918 _json = await exists(params, session, build_url(params))
919 if _json:
920 params[subdevice_type] = _json["id"]
921 _url = (
922 "https://{vcenter_hostname}"
923 # aa
924 "/api/content/subscribed-library/{library_id}?action=evict"
925 ).format(**params) + gen_args(params, _in_query_parameters)
926 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
927 try:
928 if resp.headers["Content-Type"] == "application/json":
929 _json = await resp.json()
930 except KeyError:
931 _json = {}
932 if "value" not in _json: # 7.0.2
933 _json = {"value": _json}
934
935 return await update_changed_flag(_json, resp.status, "evict")
936
937
938 async def _probe(params, session):
939 _in_query_parameters = PAYLOAD_FORMAT["probe"]["query"].keys()
940 payload = prepare_payload(params, PAYLOAD_FORMAT["probe"])
941 subdevice_type = get_subdevice_type("/api/content/subscribed-library?action=probe")
942 if subdevice_type and not params[subdevice_type]:
943 _json = await exists(params, session, build_url(params))
944 if _json:
945 params[subdevice_type] = _json["id"]
946 _url = (
947 "https://{vcenter_hostname}"
948 # aa
949 "/api/content/subscribed-library?action=probe"
950 ).format(**params) + gen_args(params, _in_query_parameters)
951 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
952 try:
953 if resp.headers["Content-Type"] == "application/json":
954 _json = await resp.json()
955 except KeyError:
956 _json = {}
957 if "value" not in _json: # 7.0.2
958 _json = {"value": _json}
959
960 return await update_changed_flag(_json, resp.status, "probe")
961
962
963 async def _sync(params, session):
964 _in_query_parameters = PAYLOAD_FORMAT["sync"]["query"].keys()
965 payload = prepare_payload(params, PAYLOAD_FORMAT["sync"])
966 subdevice_type = get_subdevice_type(
967 "/api/content/subscribed-library/{library_id}?action=sync"
968 )
969 if subdevice_type and not params[subdevice_type]:
970 _json = await exists(params, session, build_url(params))
971 if _json:
972 params[subdevice_type] = _json["id"]
973 _url = (
974 "https://{vcenter_hostname}"
975 # aa
976 "/api/content/subscribed-library/{library_id}?action=sync"
977 ).format(**params) + gen_args(params, _in_query_parameters)
978 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
979 try:
980 if resp.headers["Content-Type"] == "application/json":
981 _json = await resp.json()
982 except KeyError:
983 _json = {}
984 if "value" not in _json: # 7.0.2
985 _json = {"value": _json}
986
987 return await update_changed_flag(_json, resp.status, "sync")
988
989
990 async def _update(params, session):
991 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
992 _url = (
993 "https://{vcenter_hostname}" "/api/content/subscribed-library/{library_id}"
994 ).format(**params)
995 async with session.get(_url, **session_timeout(params)) as resp:
996 _json = await resp.json()
997 if "value" in _json:
998 value = _json["value"]
999 else: # 7.0.2 and greater
1000 value = _json
1001 for k, v in value.items():
1002 if k in payload:
1003 if isinstance(payload[k], dict) and isinstance(v, dict):
1004 to_delete = True
1005 for _k in list(payload[k].keys()):
1006 if payload[k][_k] != v.get(_k):
1007 to_delete = False
1008 if to_delete:
1009 del payload[k]
1010 elif payload[k] == v:
1011 del payload[k]
1012 elif payload[k] == {}:
1013 del payload[k]
1014
1015 if payload == {} or payload == {"spec": {}}:
1016 # Nothing has changed
1017 if "value" not in _json: # 7.0.2
1018 _json = {"value": _json}
1019 _json["id"] = params.get("library_id")
1020 return await update_changed_flag(_json, resp.status, "get")
1021 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
1022 try:
1023 if resp.headers["Content-Type"] == "application/json":
1024 _json = await resp.json()
1025 except KeyError:
1026 _json = {}
1027 if "value" not in _json: # 7.0.2
1028 _json = {"value": _json}
1029
1030 # e.g: content_configuration
1031 if not _json and resp.status == 204:
1032 async with session.get(_url, **session_timeout(params)) as resp_get:
1033 _json_get = await resp_get.json()
1034 if _json_get:
1035 _json = _json_get
1036
1037 _json["id"] = params.get("library_id")
1038 return await update_changed_flag(_json, resp.status, "update")
1039
1040
1041 if __name__ == "__main__":
1042 import asyncio
1043
1044 current_loop = asyncio.new_event_loop()
1045 try:
1046 asyncio.set_event_loop(current_loop)
1047 current_loop.run_until_complete(main())
1048 finally:
1049 current_loop.close()