Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_guest_power_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: vcenter_vm_guest_power_info
12 short_description: Returns information about the guest operating system power state.
13 description: Returns information about the guest operating system power state.
14 options:
15 session_timeout:
16 description:
17 - 'Timeout settings for client session. '
18 - 'The maximal number of seconds for the whole operation including connection
19 establishment, request sending and response. '
20 - The default value is 300s.
21 type: float
22 version_added: 2.1.0
23 vcenter_hostname:
24 description:
25 - The hostname or IP address of the vSphere vCenter
26 - If the value is not specified in the task, the value of environment variable
27 C(VMWARE_HOST) will be used instead.
28 required: true
29 type: str
30 vcenter_password:
31 description:
32 - The vSphere vCenter password
33 - If the value is not specified in the task, the value of environment variable
34 C(VMWARE_PASSWORD) will be used instead.
35 required: true
36 type: str
37 vcenter_rest_log_file:
38 description:
39 - 'You can use this optional parameter to set the location of a log file. '
40 - 'This file will be used to record the HTTP REST interaction. '
41 - 'The file will be stored on the host that runs the module. '
42 - 'If the value is not specified in the task, the value of '
43 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
44 type: str
45 vcenter_username:
46 description:
47 - The vSphere vCenter username
48 - If the value is not specified in the task, the value of environment variable
49 C(VMWARE_USER) will be used instead.
50 required: true
51 type: str
52 vcenter_validate_certs:
53 default: true
54 description:
55 - Allows connection when SSL certificates are not valid. Set to C(false) when
56 certificates are not trusted.
57 - If the value is not specified in the task, the value of environment variable
58 C(VMWARE_VALIDATE_CERTS) will be used instead.
59 type: bool
60 vm:
61 description:
62 - Identifier of the virtual machine.
63 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
64 Required with I(state=['get'])
65 type: str
66 author:
67 - Ansible Cloud Team (@ansible-collections)
68 version_added: 0.1.0
69 requirements:
70 - vSphere 7.0.3 or greater
71 - python >= 3.6
72 - aiohttp
73 notes:
74 - Tested on vSphere 7.0.3
75 """
76
77 EXAMPLES = r"""
78 - name: Create a VM
79 vmware.vmware_rest.vcenter_vm:
80 placement:
81 cluster: "{{ lookup('vmware.vmware_rest.cluster_moid', '/my_dc/host/my_cluster') }}"
82 datastore: "{{ lookup('vmware.vmware_rest.datastore_moid', '/my_dc/datastore/local') }}"
83 folder: "{{ lookup('vmware.vmware_rest.folder_moid', '/my_dc/vm') }}"
84 resource_pool: "{{ lookup('vmware.vmware_rest.resource_pool_moid', '/my_dc/host/my_cluster/Resources') }}"
85 name: test_vm1
86 guest_OS: RHEL_7_64
87 hardware_version: VMX_11
88 memory:
89 hot_add_enabled: true
90 size_MiB: 1024
91 disks:
92 - type: SATA
93 backing:
94 type: VMDK_FILE
95 vmdk_file: '[local] test_vm1/{{ disk_name }}.vmdk'
96 - type: SATA
97 new_vmdk:
98 name: second_disk
99 capacity: 32000000000
100 cdroms:
101 - type: SATA
102 sata:
103 bus: 0
104 unit: 2
105 nics:
106 - backing:
107 type: STANDARD_PORTGROUP
108 network: "{{ lookup('vmware.vmware_rest.network_moid', '/my_dc/network/VM Network') }}"
109 register: my_vm
110
111 - name: Read the power status of the VM
112 vmware.vmware_rest.vcenter_vm_guest_power_info:
113 vm: '{{ my_vm.id }}'
114 """
115 RETURN = r"""
116 # content generated by the update_return_section callback# task: Read the power status of the VM
117 value:
118 description: Read the power status of the VM
119 returned: On success
120 sample:
121 operations_ready: 0
122 state: NOT_RUNNING
123 type: dict
124 """
125
126
127 # This structure describes the format of the data expected by the end-points
128 PAYLOAD_FORMAT = {
129 "get": {"query": {}, "body": {}, "path": {"vm": "vm"}}
130 } # pylint: disable=line-too-long
131
132 from ansible.module_utils.basic import env_fallback
133 import os
134
135 if os.getenv("VMWARE_ENABLE_TURBO", False):
136 try:
137 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
138 AnsibleTurboModule as AnsibleModule,
139 )
140
141 AnsibleModule.collection_name = "vmware.vmware_rest"
142 except ImportError:
143 from ansible.module_utils.basic import AnsibleModule
144 else:
145 from ansible.module_utils.basic import AnsibleModule
146
147 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
148 gen_args,
149 open_session,
150 session_timeout,
151 update_changed_flag,
152 )
153
154
155 def prepare_argument_spec():
156 argument_spec = {
157 "vcenter_hostname": dict(
158 type="str",
159 required=True,
160 fallback=(env_fallback, ["VMWARE_HOST"]),
161 ),
162 "vcenter_username": dict(
163 type="str",
164 required=True,
165 fallback=(env_fallback, ["VMWARE_USER"]),
166 ),
167 "vcenter_password": dict(
168 type="str",
169 required=True,
170 no_log=True,
171 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
172 ),
173 "vcenter_validate_certs": dict(
174 type="bool",
175 required=False,
176 default=True,
177 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
178 ),
179 "vcenter_rest_log_file": dict(
180 type="str",
181 required=False,
182 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
183 ),
184 "session_timeout": dict(
185 type="float",
186 required=False,
187 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
188 ),
189 }
190
191 argument_spec["vm"] = {"type": "str"}
192
193 return argument_spec
194
195
196 async def main():
197 required_if = list([])
198
199 module_args = prepare_argument_spec()
200 module = AnsibleModule(
201 argument_spec=module_args, required_if=required_if, supports_check_mode=True
202 )
203 if not module.params["vcenter_hostname"]:
204 module.fail_json("vcenter_hostname cannot be empty")
205 if not module.params["vcenter_username"]:
206 module.fail_json("vcenter_username cannot be empty")
207 if not module.params["vcenter_password"]:
208 module.fail_json("vcenter_password cannot be empty")
209 try:
210 session = await open_session(
211 vcenter_hostname=module.params["vcenter_hostname"],
212 vcenter_username=module.params["vcenter_username"],
213 vcenter_password=module.params["vcenter_password"],
214 validate_certs=module.params["vcenter_validate_certs"],
215 log_file=module.params["vcenter_rest_log_file"],
216 )
217 except Exception as err:
218 if hasattr(err, "get_message"):
219 module.fail_json(err.get_message())
220 else:
221 module.fail_json(str(err))
222 result = await entry_point(module, session)
223 module.exit_json(**result)
224
225
226 # template: info_no_list_module.j2
227 def build_url(params):
228 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/guest/power").format(
229 **params
230 )
231
232
233 async def entry_point(module, session):
234 return await _info(module.params, session)
235
236
237 async def _info(params, session):
238 payload_format = list(PAYLOAD_FORMAT.values())[0]
239 _in_query_parameters = payload_format["query"].keys()
240 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/guest/power").format(
241 **params
242 ) + gen_args(params, _in_query_parameters)
243 async with session.get(_url, **session_timeout(params)) as resp:
244 try:
245 if resp.headers["Content-Type"] == "application/json":
246 _json = await resp.json()
247 except KeyError:
248 _json = {}
249 return await update_changed_flag(_json, resp.status, "get")
250
251
252 if __name__ == "__main__":
253 import asyncio
254
255 current_loop = asyncio.new_event_loop()
256 try:
257 asyncio.set_event_loop(current_loop)
258 current_loop.run_until_complete(main())
259 finally:
260 current_loop.close()