Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/content_library_item_info.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_library_item_info
12 short_description: Returns the ItemModel with the given identifier.
13 description: Returns the ItemModel with the given identifier.
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.content_library_item_info) instead.
18 options:
19 library_id:
20 description:
21 - Identifier of the library whose items should be returned.
22 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.content_library_info).
23 Required with I(state=['list'])
24 type: str
25 library_item_id:
26 description:
27 - Identifier of the library item to return.
28 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.content_library_item_info).
29 Required with I(state=['get'])
30 type: str
31 session_timeout:
32 description:
33 - 'Timeout settings for client session. '
34 - 'The maximal number of seconds for the whole operation including connection
35 establishment, request sending and response. '
36 - The default value is 300s.
37 type: float
38 version_added: 2.1.0
39 vcenter_hostname:
40 description:
41 - The hostname or IP address of the vSphere vCenter
42 - If the value is not specified in the task, the value of environment variable
43 C(VMWARE_HOST) will be used instead.
44 required: true
45 type: str
46 vcenter_password:
47 description:
48 - The vSphere vCenter password
49 - If the value is not specified in the task, the value of environment variable
50 C(VMWARE_PASSWORD) will be used instead.
51 required: true
52 type: str
53 vcenter_rest_log_file:
54 description:
55 - 'You can use this optional parameter to set the location of a log file. '
56 - 'This file will be used to record the HTTP REST interaction. '
57 - 'The file will be stored on the host that runs the module. '
58 - 'If the value is not specified in the task, the value of '
59 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
60 type: str
61 vcenter_username:
62 description:
63 - The vSphere vCenter username
64 - If the value is not specified in the task, the value of environment variable
65 C(VMWARE_USER) will be used instead.
66 required: true
67 type: str
68 vcenter_validate_certs:
69 default: true
70 description:
71 - Allows connection when SSL certificates are not valid. Set to C(false) when
72 certificates are not trusted.
73 - If the value is not specified in the task, the value of environment variable
74 C(VMWARE_VALIDATE_CERTS) will be used instead.
75 type: bool
76 author:
77 - Ansible Cloud Team (@ansible-collections)
78 version_added: 2.0.0
79 requirements:
80 - vSphere 7.0.3 or greater
81 - python >= 3.6
82 - aiohttp
83 notes:
84 - Tested on vSphere 7.0.3
85 """
86
87 EXAMPLES = r"""
88 - name: Create a content library pointing on a NFS share
89 vmware.vmware_rest.content_locallibrary:
90 name: my_library_on_nfs
91 description: automated
92 publish_info:
93 published: true
94 authentication_method: NONE
95 storage_backings:
96 - storage_uri: nfs://datastore.test/srv/share/content-library
97 type: OTHER
98 state: present
99 register: nfs_lib
100
101 - name: Get the list of items of the NFS library
102 vmware.vmware_rest.content_library_item_info:
103 library_id: '{{ nfs_lib.id }}'
104 register: lib_items
105
106 - name: Get the list of items of the NFS library
107 vmware.vmware_rest.content_library_item_info:
108 library_id: '{{ nfs_lib.id }}'
109 register: result
110
111 - name: Create a new local content library
112 vmware.vmware_rest.content_locallibrary:
113 name: local_library_001
114 description: automated
115 publish_info:
116 published: true
117 authentication_method: NONE
118 storage_backings:
119 - datastore_id: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/rw_datastore') }}"
120 type: DATASTORE
121 state: present
122 register: ds_lib
123
124 - name: Get the (empty) list of items of the library
125 vmware.vmware_rest.content_library_item_info:
126 library_id: '{{ ds_lib.id }}'
127 register: result
128
129 - name: Create subscribed library
130 vmware.vmware_rest.content_subscribedlibrary:
131 name: sub_lib
132 subscription_info:
133 subscription_url: '{{ nfs_lib.value.publish_info.publish_url }}'
134 authentication_method: NONE
135 automatic_sync_enabled: false
136 on_demand: true
137 storage_backings:
138 - datastore_id: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/rw_datastore') }}"
139 type: DATASTORE
140 register: sub_lib
141
142 - name: Ensure the OVF is here
143 vmware.vmware_rest.content_library_item_info:
144 library_id: '{{ sub_lib.id }}'
145 register: result
146
147 - name: Create a content library based on a DataStore
148 vmware.vmware_rest.content_locallibrary:
149 name: my_library_on_datastore
150 description: automated
151 publish_info:
152 published: true
153 authentication_method: NONE
154 storage_backings:
155 - datastore_id: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/local') }}"
156 type: DATASTORE
157 state: present
158 register: nfs_lib
159 """
160 RETURN = r"""
161 # content generated by the update_return_section callback# task: Ensure the OVF is here
162 value:
163 description: Ensure the OVF is here
164 returned: On success
165 sample:
166 - cached: 0
167 content_version: '2'
168 creation_time: '2022-11-23T20:06:05.707Z'
169 description: an OVF example
170 id: f6618d6b-301b-4202-aa9c-12eb0c7536b1
171 last_modified_time: '2022-11-23T20:06:06.062Z'
172 last_sync_time: '2022-11-23T20:06:06.061Z'
173 library_id: 8b4e355e-a463-44f1-9b04-d0786a49cc7d
174 metadata_version: '1'
175 name: golden_image
176 security_compliance: 1
177 size: 0
178 source_id: 636ef270-b556-4972-924f-0d21b0f3bfce
179 type: ovf
180 version: '1'
181 type: list
182 """
183
184
185 # This structure describes the format of the data expected by the end-points
186 PAYLOAD_FORMAT = {
187 "get": {"query": {}, "body": {}, "path": {"library_item_id": "library_item_id"}},
188 "list": {"query": {"library_id": "library_id"}, "body": {}, "path": {}},
189 } # pylint: disable=line-too-long
190
191 from ansible.module_utils.basic import env_fallback
192 import os
193
194 if os.getenv("VMWARE_ENABLE_TURBO", False):
195 try:
196 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
197 AnsibleTurboModule as AnsibleModule,
198 )
199
200 AnsibleModule.collection_name = "vmware.vmware_rest"
201 except ImportError:
202 from ansible.module_utils.basic import AnsibleModule
203 else:
204 from ansible.module_utils.basic import AnsibleModule
205
206 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
207 build_full_device_list,
208 exists,
209 gen_args,
210 open_session,
211 session_timeout,
212 update_changed_flag,
213 )
214
215
216 def prepare_argument_spec():
217 argument_spec = {
218 "vcenter_hostname": dict(
219 type="str",
220 required=True,
221 fallback=(env_fallback, ["VMWARE_HOST"]),
222 ),
223 "vcenter_username": dict(
224 type="str",
225 required=True,
226 fallback=(env_fallback, ["VMWARE_USER"]),
227 ),
228 "vcenter_password": dict(
229 type="str",
230 required=True,
231 no_log=True,
232 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
233 ),
234 "vcenter_validate_certs": dict(
235 type="bool",
236 required=False,
237 default=True,
238 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
239 ),
240 "vcenter_rest_log_file": dict(
241 type="str",
242 required=False,
243 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
244 ),
245 "session_timeout": dict(
246 type="float",
247 required=False,
248 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
249 ),
250 }
251
252 argument_spec["library_id"] = {"type": "str"}
253 argument_spec["library_item_id"] = {"type": "str"}
254
255 return argument_spec
256
257
258 async def main():
259 required_if = list([])
260
261 module_args = prepare_argument_spec()
262 module = AnsibleModule(
263 argument_spec=module_args, required_if=required_if, supports_check_mode=True
264 )
265 if not module.params["vcenter_hostname"]:
266 module.fail_json("vcenter_hostname cannot be empty")
267 if not module.params["vcenter_username"]:
268 module.fail_json("vcenter_username cannot be empty")
269 if not module.params["vcenter_password"]:
270 module.fail_json("vcenter_password cannot be empty")
271 try:
272 session = await open_session(
273 vcenter_hostname=module.params["vcenter_hostname"],
274 vcenter_username=module.params["vcenter_username"],
275 vcenter_password=module.params["vcenter_password"],
276 validate_certs=module.params["vcenter_validate_certs"],
277 log_file=module.params["vcenter_rest_log_file"],
278 )
279 except Exception as err:
280 if hasattr(err, "get_message"):
281 module.fail_json(err.get_message())
282 else:
283 module.fail_json(str(err))
284 result = await entry_point(module, session)
285 module.exit_json(**result)
286
287
288 # template: info_list_and_get_module.j2
289 def build_url(params):
290 import yarl
291
292 if params.get("library_item_id"):
293 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
294 return yarl.URL(
295 ("https://{vcenter_hostname}" "/api/content/library/item/").format(**params)
296 + params["library_item_id"]
297 + gen_args(params, _in_query_parameters),
298 encoded=True,
299 )
300 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
301 return yarl.URL(
302 ("https://{vcenter_hostname}" "/api/content/library/item?library_id").format(
303 **params
304 )
305 + gen_args(params, _in_query_parameters),
306 encoded=True,
307 )
308
309
310 async def entry_point(module, session):
311 url = build_url(module.params)
312 async with session.get(url, **session_timeout(module.params)) as resp:
313 _json = await resp.json()
314
315 if "value" not in _json: # 7.0.2+
316 _json = {"value": _json}
317
318 if module.params.get("library_item_id"):
319 _json["id"] = module.params.get("library_item_id")
320 elif module.params.get("label"): # TODO extend the list of filter
321 _json = await exists(module.params, session, str(url))
322 elif (
323 isinstance(_json["value"], list)
324 and len(_json["value"]) > 0
325 and isinstance(_json["value"][0], str)
326 ):
327 # this is a list of id, we fetch the details
328 full_device_list = await build_full_device_list(session, str(url), _json)
329 _json = {"value": [i["value"] for i in full_device_list]}
330
331 return await update_changed_flag(_json, resp.status, "get")
332
333
334 if __name__ == "__main__":
335 import asyncio
336
337 current_loop = asyncio.new_event_loop()
338 try:
339 asyncio.set_event_loop(current_loop)
340 current_loop.run_until_complete(main())
341 finally:
342 current_loop.close()