Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vmtemplate_libraryitems.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: vcenter_vmtemplate_libraryitems
12 short_description: Creates a library item in content library from a virtual machine
13 description: Creates a library item in content library from a virtual machine. This
14 operation creates a library item in content library whose content is a virtual
15 machine template created from the source virtual machine, using the supplied create
16 specification. The virtual machine template is stored in a newly created library
17 item.
18 options:
19 description:
20 description:
21 - Description of the deployed virtual machine.
22 - If unset, the deployed virtual machine has the same description as the source
23 library item.
24 type: str
25 disk_storage:
26 description:
27 - Storage specification for the deployed virtual machine's disks.
28 - 'If both I(disk_storage_overrides) and I(disk_storage) are unset, the deployed
29 virtual machine''s disks are created with the same storage spec as the
30 corresponding disks in the source virtual machine template contained in
31 the library item. '
32 - ' If I(disk_storage_overrides) is unset and I(disk_storage) is specified,
33 all of the deployed virtual machine''s disks are created with the storage
34 spec specified by I(disk_storage). '
35 - ''
36 - ' If I(disk_storage_overrides) is specified and I(disk_storage) is unset,
37 disks with identifiers that are not in I(disk_storage_overrides) are created
38 with the same storage spec as the corresponding disks in the source virtual
39 machine template contained in the library item. '
40 - ''
41 - ' If both I(disk_storage_overrides) and I(disk_storage) are specified, disks
42 with identifiers that are not in I(disk_storage_overrides) are created
43 with the storage spec specified by I(disk_storage).'
44 - 'Valid attributes are:'
45 - ' - C(datastore) (str): Identifier for the datastore associated the deployed
46 virtual machine''s disk.'
47 - 'This field is currently required. '
48 - ' If I(storage_policy) is also specified and is incompatible with the I(datastore),
49 then the disk will be flagged as being out of compliance with the specified
50 storage policy.'
51 - ''
52 - When clients pass a value of this structure as a parameter, the field must
53 be the id of a resource returned by M(vmware.vmware_rest.vcenter_datastore_info).
54 (['deploy', 'present'])
55 - ' - C(storage_policy) (dict): Storage policy for the deployed virtual machine''s
56 disk.'
57 - If unset, I(datastore) must be specified and the deployed virtual machine's
58 disk is created with the default storage policy associated with the I(datastore).
59 (['deploy', 'present'])
60 - ' - Accepted keys:'
61 - ' - type (string): Policy type for a virtual machine template''s disk.'
62 - 'Accepted value for this field:'
63 - ' - C(USE_SPECIFIED_POLICY)'
64 - ' - policy (string): Identifier for the storage policy to use.'
65 - This field is optional and it is only relevant when the value of I(type)
66 is USE_SPECIFIED_POLICY.
67 - 'When clients pass a value of this structure as a parameter, the field must
68 be the id of a resource returned by M(vmware.vmware_rest.vcenter_storage_policies_info). '
69 type: dict
70 disk_storage_overrides:
71 description:
72 - Storage specification for individual disks in the deployed virtual machine.
73 This is specified as a mapping between disk identifiers in the source
74 virtual machine template contained in the library item and their storage
75 specifications.
76 - 'If both I(disk_storage_overrides) and I(disk_storage) are unset, the deployed
77 virtual machine''s disks are created with the same storage spec as the
78 corresponding disks in the source virtual machine template contained in
79 the library item. '
80 - ' If I(disk_storage_overrides) is unset and I(disk_storage) is specified,
81 all of the deployed virtual machine''s disks are created with the storage
82 spec specified by I(disk_storage). '
83 - ''
84 - ' If I(disk_storage_overrides) is specified and I(disk_storage) is unset,
85 disks with identifiers that are not in I(disk_storage_overrides) are created
86 with the same storage spec as the corresponding disks in the source virtual
87 machine template contained in the library item. '
88 - ''
89 - ' If both I(disk_storage_overrides) and I(disk_storage) are specified, disks
90 with identifiers that are not in I(disk_storage_overrides) are created
91 with the storage spec specified by I(disk_storage). '
92 - ''
93 - 'When clients pass a value of this structure as a parameter, the key in
94 the field map must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_disk). '
95 type: dict
96 guest_customization:
97 description:
98 - Guest customization spec to apply to the deployed virtual machine.
99 - If unset, the guest operating system is not customized after deployment.
100 - 'Valid attributes are:'
101 - ' - C(name) (str): Name of the customization specification.'
102 - If unset, no guest customization is performed. (['deploy'])
103 type: dict
104 hardware_customization:
105 description:
106 - Hardware customization spec which specifies updates to the deployed virtual
107 machine.
108 - If unset, the deployed virtual machine has the same hardware configuration
109 as the source virtual machine template contained in the library item.
110 - 'Valid attributes are:'
111 - ' - C(nics) (dict): Map of Ethernet network adapters to update.'
112 - If unset, all Ethernet adapters will remain connected to the same network
113 as they were in the source virtual machine template. An Ethernet adapter
114 with a MacAddressType of MANUAL will not change. An Ethernet adapter with
115 a MacAddressType of GENERATED or ASSIGNED will receive a new address.
116 - When clients pass a value of this structure as a parameter, the key in the
117 field map must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_ethernet).
118 (['deploy'])
119 - ' - C(disks_to_remove) (list): Idenfiers of disks to remove from the deployed
120 virtual machine.'
121 - If unset, all disks will be copied.
122 - When clients pass a value of this structure as a parameter, the field must
123 contain the id of resources returned by M(vmware.vmware_rest.vcenter_vm_hardware_disk).
124 (['deploy'])
125 - ' - C(disks_to_update) (dict): Disk update specification for individual
126 disks in the deployed virtual machine.'
127 - If unset, disks in the deployed virtual machine will have the same settings
128 as the corresponding disks in the source virtual machine template contained
129 in the library item.
130 - When clients pass a value of this structure as a parameter, the key in the
131 field map must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_disk).
132 (['deploy'])
133 - ' - C(cpu_update) (dict): CPU update specification for the deployed virtual
134 machine.'
135 - If {@term.unset}, the deployed virtual machine has the same CPU settings
136 as the source virtual machine template contained in the library item.
137 (['deploy'])
138 - ' - Accepted keys:'
139 - ' - num_cpus (integer): Number of virtual processors in the deployed
140 virtual machine.'
141 - If {@term.unset}, the deployed virtual machine has the same CPU count as
142 the source virtual machine template contained in the library item.
143 - ' - num_cores_per_socket (integer): Number of cores among which to distribute
144 CPUs in the deployed virtual machine.'
145 - If {@term.unset}, the deployed virtual machine has the same number of cores
146 per socket as the source virtual machine template contained in the library
147 item.
148 - ' - C(memory_update) (dict): Memory update specification for the deployed
149 virtual machine.'
150 - If {@term.unset}, the deployed virtual machine has the same memory settings
151 as the source virtual machine template contained in the library item.
152 (['deploy'])
153 - ' - Accepted keys:'
154 - ' - memory (integer): Size of a virtual machine''s memory in MB.'
155 - If {@term.unset}, the deployed virtual machine has the same memory size
156 as the source virtual machine template.
157 type: dict
158 library:
159 description:
160 - Identifier of the library in which the new library item should be created.
161 - When clients pass a value of this structure as a parameter, the field must
162 be the id of a resource returned by M(vmware.vmware_rest.content_library_info).
163 Required with I(state=['present'])
164 type: str
165 name:
166 description:
167 - Name of the deployed virtual machine. This parameter is mandatory.
168 required: true
169 type: str
170 placement:
171 description:
172 - Information used to place the deployed virtual machine.
173 - 'This field is currently required. In the future, if this field is unset,
174 the system will use the values from the source virtual machine template
175 contained in the library item. '
176 - ' If specified, each field will be used for placement. If the fields result
177 in disjoint placement, the operation will fail. If the fields along with
178 the placement values of the source virtual machine template result in
179 disjoint placement, the operation will fail.'
180 - 'Valid attributes are:'
181 - ' - C(folder) (str): Virtual machine folder into which the deployed virtual
182 machine should be placed.'
183 - 'This field is currently required. '
184 - ' If unset, the system will attempt to choose a suitable folder for the
185 virtual machine; if a folder cannot be chosen, the virtual machine deployment
186 operation will fail. '
187 - ''
188 - When clients pass a value of this structure as a parameter, the field must
189 be the id of a resource returned by M(vmware.vmware_rest.vcenter_folder_info).
190 (['deploy', 'present'])
191 - ' - C(resource_pool) (str): Resource pool into which the deployed virtual
192 machine should be placed.'
193 - If unset, the system will attempt to choose a suitable resource pool for
194 the virtual machine; if a resource pool cannot be chosen, the virtual
195 machine deployment operation will fail.
196 - When clients pass a value of this structure as a parameter, the field must
197 be the id of a resource returned by M(vmware.vmware_rest.vcenter_resourcepool_info).
198 (['deploy', 'present'])
199 - ' - C(host) (str): Host onto which the virtual machine should be placed.
200 If I(host) and I(resource_pool) are both specified, I(resource_pool) must
201 belong to I(host). If I(host) and I(cluster) are both specified, I(host)
202 must be a member of I(cluster).'
203 - This field may be unset if I(resource_pool) or I(cluster) is specified.
204 If unset, the system will attempt to choose a suitable host for the virtual
205 machine; if a host cannot be chosen, the virtual machine deployment operation
206 will fail.
207 - When clients pass a value of this structure as a parameter, the field must
208 be the id of a resource returned by M(vmware.vmware_rest.vcenter_host_info).
209 (['deploy', 'present'])
210 - ' - C(cluster) (str): Cluster onto which the deployed virtual machine should
211 be placed. If I(cluster) and I(resource_pool) are both specified, I(resource_pool)
212 must belong to I(cluster). If I(cluster) and I(host) are both specified,
213 I(host) must be a member of I(cluster).'
214 - If I(resource_pool) or I(host) is specified, it is recommended that this
215 field be unset.
216 - When clients pass a value of this structure as a parameter, the field must
217 be the id of a resource returned by M(vmware.vmware_rest.vcenter_cluster_info).
218 (['deploy', 'present'])
219 type: dict
220 powered_on:
221 description:
222 - Specifies whether the deployed virtual machine should be powered on after
223 deployment.
224 - If unset, the virtual machine will not be powered on after deployment.
225 type: bool
226 session_timeout:
227 description:
228 - 'Timeout settings for client session. '
229 - 'The maximal number of seconds for the whole operation including connection
230 establishment, request sending and response. '
231 - The default value is 300s.
232 type: float
233 version_added: 2.1.0
234 source_vm:
235 description:
236 - Identifier of the source virtual machine to create the library item from.
237 - When clients pass a value of this structure as a parameter, the field must
238 be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
239 Required with I(state=['present'])
240 type: str
241 state:
242 choices:
243 - deploy
244 - present
245 default: present
246 description: []
247 type: str
248 template_library_item:
249 description:
250 - identifier of the content library item containing the source virtual machine
251 template to be deployed.
252 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.content_library_item_info).
253 Required with I(state=['deploy'])
254 type: str
255 vcenter_hostname:
256 description:
257 - The hostname or IP address of the vSphere vCenter
258 - If the value is not specified in the task, the value of environment variable
259 C(VMWARE_HOST) will be used instead.
260 required: true
261 type: str
262 vcenter_password:
263 description:
264 - The vSphere vCenter password
265 - If the value is not specified in the task, the value of environment variable
266 C(VMWARE_PASSWORD) will be used instead.
267 required: true
268 type: str
269 vcenter_rest_log_file:
270 description:
271 - 'You can use this optional parameter to set the location of a log file. '
272 - 'This file will be used to record the HTTP REST interaction. '
273 - 'The file will be stored on the host that runs the module. '
274 - 'If the value is not specified in the task, the value of '
275 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
276 type: str
277 vcenter_username:
278 description:
279 - The vSphere vCenter username
280 - If the value is not specified in the task, the value of environment variable
281 C(VMWARE_USER) will be used instead.
282 required: true
283 type: str
284 vcenter_validate_certs:
285 default: true
286 description:
287 - Allows connection when SSL certificates are not valid. Set to C(false) when
288 certificates are not trusted.
289 - If the value is not specified in the task, the value of environment variable
290 C(VMWARE_VALIDATE_CERTS) will be used instead.
291 type: bool
292 vm_home_storage:
293 description:
294 - Storage location for the virtual machine template's configuration and log
295 files.
296 - If unset, the virtual machine template's configuration and log files are
297 placed on the default storage backing associated with the library specified
298 by I()
299 - 'Valid attributes are:'
300 - ' - C(datastore) (str): Identifier of the datastore for the deployed virtual
301 machine''s configuration and log files.'
302 - 'This field is currently required. '
303 - ' When I(storage_policy) is also specified and is incompatible with the
304 I(datastore), then the deployed virtual machine will be flagged as being
305 out of compliance with the specified storage policy.'
306 - ''
307 - When clients pass a value of this structure as a parameter, the field must
308 be the id of a resource returned by M(vmware.vmware_rest.vcenter_datastore_info).
309 (['deploy', 'present'])
310 - ' - C(storage_policy) (dict): Storage policy for the deployed virtual machine''s
311 configuration and log files.'
312 - If unset, I(datastore) must be specified and the deployed virtual machine's
313 configuration and log files are created with the default storage policy
314 associated with the I(datastore). (['deploy', 'present'])
315 - ' - Accepted keys:'
316 - ' - type (string): Policy type for the virtual machine template''s configuration
317 and log files.'
318 - 'Accepted value for this field:'
319 - ' - C(USE_SPECIFIED_POLICY)'
320 - ' - policy (string): Identifier for the storage policy to use.'
321 - This field is optional and it is only relevant when the value of I(type)
322 is USE_SPECIFIED_POLICY.
323 - 'When clients pass a value of this structure as a parameter, the field must
324 be the id of a resource returned by M(vmware.vmware_rest.vcenter_storage_policies_info). '
325 type: dict
326 author:
327 - Ansible Cloud Team (@ansible-collections)
328 version_added: 2.2.0
329 requirements:
330 - vSphere 7.0.3 or greater
331 - python >= 3.6
332 - aiohttp
333 notes:
334 - Tested on vSphere 7.0.3
335 """
336
337 EXAMPLES = r"""
338 - name: Create a VM
339 vmware.vmware_rest.vcenter_vm:
340 placement:
341 cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
342 datastore: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/local') }}"
343 folder: "{{ lookup('vmware.vmware_rest.folder_moid', '/my_dc/vm') }}"
344 resource_pool: "{{ lookup('vmware.vmware_rest.resource_pool_moid', '/my_dc/host/my_cluster/Resources') }}"
345 name: test_vm1
346 guest_OS: RHEL_7_64
347 hardware_version: VMX_11
348 memory:
349 hot_add_enabled: true
350 size_MiB: 1024
351 register: my_vm
352
353 - name: Create a content library based on a DataStore
354 vmware.vmware_rest.content_locallibrary:
355 name: my_library_on_datastore
356 description: automated
357 publish_info:
358 published: true
359 authentication_method: NONE
360 storage_backings:
361 - datastore_id: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/local') }}"
362 type: DATASTORE
363 state: present
364 register: nfs_lib
365
366 - name: Create a VM template on the library
367 vmware.vmware_rest.vcenter_vmtemplate_libraryitems:
368 name: golden-template
369 library: '{{ nfs_lib.id }}'
370 source_vm: '{{ my_vm.id }}'
371 placement:
372 cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
373 folder: "{{ lookup('vmware.vmware_rest.folder_moid', '/my_dc/vm') }}"
374 resource_pool: "{{ lookup('vmware.vmware_rest.resource_pool_moid', '/my_dc/host/my_cluster/Resources') }}"
375 register: mylib_item
376
377 - name: Deploy a new VM based on the template
378 vmware.vmware_rest.vcenter_vmtemplate_libraryitems:
379 name: vm-from-template
380 library: '{{ nfs_lib.id }}'
381 template_library_item: '{{ mylib_item.id }}'
382 placement:
383 cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
384 folder: "{{ lookup('vmware.vmware_rest.folder_moid', '/my_dc/vm') }}"
385 resource_pool: "{{ lookup('vmware.vmware_rest.resource_pool_moid', '/my_dc/host/my_cluster/Resources') }}"
386 state: deploy
387 register: my_new_vm
388 """
389 RETURN = r"""
390 # content generated by the update_return_section callback# task: Create a VM template on the library
391 id:
392 description: moid of the resource
393 returned: On success
394 sample: 9c6df1f5-faba-490c-a8e6-edb72f787ab8
395 type: str
396 value:
397 description: Create a VM template on the library
398 returned: On success
399 sample:
400 cpu:
401 cores_per_socket: 1
402 count: 1
403 disks:
404 '16000':
405 capacity: 32000000000
406 disk_storage:
407 datastore: datastore-3036
408 guest_OS: RHEL_7_64
409 memory:
410 size_MiB: 1024
411 nics: {}
412 vm_home_storage:
413 datastore: datastore-3036
414 vm_template: vm-77006
415 type: dict
416 """
417
418
419 # This structure describes the format of the data expected by the end-points
420 PAYLOAD_FORMAT = {
421 "create": {
422 "query": {},
423 "body": {
424 "description": "description",
425 "disk_storage": "disk_storage",
426 "disk_storage_overrides": "disk_storage_overrides",
427 "library": "library",
428 "name": "name",
429 "placement": "placement",
430 "source_vm": "source_vm",
431 "vm_home_storage": "vm_home_storage",
432 },
433 "path": {},
434 },
435 "deploy": {
436 "query": {},
437 "body": {
438 "description": "description",
439 "disk_storage": "disk_storage",
440 "disk_storage_overrides": "disk_storage_overrides",
441 "guest_customization": "guest_customization",
442 "hardware_customization": "hardware_customization",
443 "name": "name",
444 "placement": "placement",
445 "powered_on": "powered_on",
446 "vm_home_storage": "vm_home_storage",
447 },
448 "path": {"template_library_item": "template_library_item"},
449 },
450 } # pylint: disable=line-too-long
451
452 from ansible.module_utils.basic import env_fallback
453 import os
454
455 if os.getenv("VMWARE_ENABLE_TURBO", False):
456 try:
457 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
458 AnsibleTurboModule as AnsibleModule,
459 )
460
461 AnsibleModule.collection_name = "vmware.vmware_rest"
462 except ImportError:
463 from ansible.module_utils.basic import AnsibleModule
464 else:
465 from ansible.module_utils.basic import AnsibleModule
466
467 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
468 exists,
469 gen_args,
470 get_device_info,
471 get_subdevice_type,
472 open_session,
473 prepare_payload,
474 session_timeout,
475 update_changed_flag,
476 )
477
478
479 def prepare_argument_spec():
480 argument_spec = {
481 "vcenter_hostname": dict(
482 type="str",
483 required=True,
484 fallback=(env_fallback, ["VMWARE_HOST"]),
485 ),
486 "vcenter_username": dict(
487 type="str",
488 required=True,
489 fallback=(env_fallback, ["VMWARE_USER"]),
490 ),
491 "vcenter_password": dict(
492 type="str",
493 required=True,
494 no_log=True,
495 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
496 ),
497 "vcenter_validate_certs": dict(
498 type="bool",
499 required=False,
500 default=True,
501 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
502 ),
503 "vcenter_rest_log_file": dict(
504 type="str",
505 required=False,
506 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
507 ),
508 "session_timeout": dict(
509 type="float",
510 required=False,
511 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
512 ),
513 }
514
515 argument_spec["description"] = {"type": "str"}
516 argument_spec["disk_storage"] = {"type": "dict"}
517 argument_spec["disk_storage_overrides"] = {"type": "dict"}
518 argument_spec["guest_customization"] = {"type": "dict"}
519 argument_spec["hardware_customization"] = {"type": "dict"}
520 argument_spec["library"] = {"type": "str"}
521 argument_spec["name"] = {"required": True, "type": "str"}
522 argument_spec["placement"] = {"type": "dict"}
523 argument_spec["powered_on"] = {"type": "bool"}
524 argument_spec["source_vm"] = {"type": "str"}
525 argument_spec["state"] = {
526 "type": "str",
527 "choices": ["deploy", "present"],
528 "default": "present",
529 }
530 argument_spec["template_library_item"] = {"type": "str"}
531 argument_spec["vm_home_storage"] = {"type": "dict"}
532
533 return argument_spec
534
535
536 async def main():
537 required_if = list([])
538
539 module_args = prepare_argument_spec()
540 module = AnsibleModule(
541 argument_spec=module_args, required_if=required_if, supports_check_mode=False
542 )
543 if not module.params["vcenter_hostname"]:
544 module.fail_json("vcenter_hostname cannot be empty")
545 if not module.params["vcenter_username"]:
546 module.fail_json("vcenter_username cannot be empty")
547 if not module.params["vcenter_password"]:
548 module.fail_json("vcenter_password cannot be empty")
549 try:
550 session = await open_session(
551 vcenter_hostname=module.params["vcenter_hostname"],
552 vcenter_username=module.params["vcenter_username"],
553 vcenter_password=module.params["vcenter_password"],
554 validate_certs=module.params["vcenter_validate_certs"],
555 log_file=module.params["vcenter_rest_log_file"],
556 )
557 except Exception as err:
558 if hasattr(err, "get_message"):
559 module.fail_json(err.get_message())
560 else:
561 module.fail_json(str(err))
562 result = await entry_point(module, session)
563 module.exit_json(**result)
564
565
566 # template: default_module.j2
567 def build_url(params):
568 return (
569 "https://{vcenter_hostname}" "/api/vcenter/vm-template/library-items"
570 ).format(**params)
571
572
573 async def entry_point(module, session):
574
575 if module.params["state"] == "present":
576 if "_create" in globals():
577 operation = "create"
578 else:
579 operation = "update"
580 elif module.params["state"] == "absent":
581 operation = "delete"
582 else:
583 operation = module.params["state"]
584
585 func = globals()["_" + operation]
586
587 return await func(module.params, session)
588
589
590 async def _create(params, session):
591
592 lookup_url = "https://{vcenter_hostname}/api/content/library/item?library_id={library}".format(
593 **params
594 )
595 per_id_url = "https://{vcenter_hostname}/api/content/library/item".format(**params)
596 uniquity_keys = ["name"]
597 comp_func = None
598
599 _json = None
600
601 if params["template_library_item"]:
602 _json = await get_device_info(
603 session, build_url(params), params["template_library_item"]
604 )
605
606 if not _json and (uniquity_keys or comp_func):
607 _json = await exists(
608 params,
609 session,
610 url=lookup_url,
611 uniquity_keys=uniquity_keys,
612 per_id_url=per_id_url,
613 comp_func=comp_func,
614 )
615
616 if _json:
617 if "value" not in _json: # 7.0.2+
618 _json = {"value": _json}
619 if "_update" in globals():
620 params["template_library_item"] = _json["id"]
621 return await globals()["_update"](params, session)
622
623 extra_info_url = "https://{vcenter_hostname}/api/vcenter/vm-template/library-items/{id}".format(
624 **params, id=_json["id"]
625 )
626 async with session.get(extra_info_url) as resp:
627 if resp.status == 200:
628 extra_json = await resp.json()
629 for k, v in extra_json.items():
630 _json["value"][k] = v
631
632 return await update_changed_flag(_json, 200, "get")
633
634 payload = prepare_payload(params, PAYLOAD_FORMAT["create"])
635 _url = (
636 "https://{vcenter_hostname}" "/api/vcenter/vm-template/library-items"
637 ).format(**params)
638 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
639 if resp.status == 500:
640 text = await resp.text()
641 raise Exception(f"Request has failed: status={resp.status}, {text}")
642 try:
643 if resp.headers["Content-Type"] == "application/json":
644 _json = await resp.json()
645 except KeyError:
646 _json = {}
647
648 if (resp.status in [200, 201]) and "error" not in _json:
649 if isinstance(_json, str): # 7.0.2 and greater
650 _id = _json # TODO: fetch the object
651 elif isinstance(_json, dict) and "value" not in _json:
652 _id = list(_json["value"].values())[0]
653 elif isinstance(_json, dict) and "value" in _json:
654 _id = _json["value"]
655 _json_device_info = await get_device_info(session, _url, _id)
656 if _json_device_info:
657 _json = _json_device_info
658
659 return await update_changed_flag(_json, resp.status, "create")
660
661
662 async def _deploy(params, session):
663 _in_query_parameters = PAYLOAD_FORMAT["deploy"]["query"].keys()
664 payload = prepare_payload(params, PAYLOAD_FORMAT["deploy"])
665 subdevice_type = get_subdevice_type(
666 "/api/vcenter/vm-template/library-items/{template_library_item}?action=deploy"
667 )
668 if subdevice_type and not params[subdevice_type]:
669 _json = await exists(params, session, build_url(params))
670 if _json:
671 params[subdevice_type] = _json["id"]
672 _url = (
673 "https://{vcenter_hostname}"
674 # aa
675 "/api/vcenter/vm-template/library-items/{template_library_item}?action=deploy"
676 ).format(**params) + gen_args(params, _in_query_parameters)
677 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
678 try:
679 if resp.headers["Content-Type"] == "application/json":
680 _json = await resp.json()
681 except KeyError:
682 _json = {}
683 if "value" not in _json: # 7.0.2
684 _json = {"value": _json}
685
686 return await update_changed_flag(_json, resp.status, "deploy")
687
688
689 if __name__ == "__main__":
690 import asyncio
691
692 current_loop = asyncio.new_event_loop()
693 try:
694 asyncio.set_event_loop(current_loop)
695 current_loop.run_until_complete(main())
696 finally:
697 current_loop.close()