Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_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_power_info
12 short_description: Returns the power state information of a virtual machine.
13 description: Returns the power state information of a virtual machine.
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 - Virtual machine identifier.
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: Look up the VM called test_vm1 in the inventory
79 register: search_result
80 vmware.vmware_rest.vcenter_vm_info:
81 filter_names:
82 - test_vm1
83
84 - name: Collect information about a specific VM
85 vmware.vmware_rest.vcenter_vm_info:
86 vm: '{{ search_result.value[0].vm }}'
87 register: test_vm1_info
88
89 - name: Get guest power information
90 vmware.vmware_rest.vcenter_vm_power_info:
91 vm: '{{ test_vm1_info.id }}'
92 register: _result
93 """
94 RETURN = r"""
95 # content generated by the update_return_section callback# task: Get guest power information
96 value:
97 description: Get guest power information
98 returned: On success
99 sample:
100 state: POWERED_ON
101 type: dict
102 """
103
104
105 # This structure describes the format of the data expected by the end-points
106 PAYLOAD_FORMAT = {
107 "get": {"query": {}, "body": {}, "path": {"vm": "vm"}}
108 } # pylint: disable=line-too-long
109
110 from ansible.module_utils.basic import env_fallback
111 import os
112
113 if os.getenv("VMWARE_ENABLE_TURBO", False):
114 try:
115 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
116 AnsibleTurboModule as AnsibleModule,
117 )
118
119 AnsibleModule.collection_name = "vmware.vmware_rest"
120 except ImportError:
121 from ansible.module_utils.basic import AnsibleModule
122 else:
123 from ansible.module_utils.basic import AnsibleModule
124
125 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
126 gen_args,
127 open_session,
128 session_timeout,
129 update_changed_flag,
130 )
131
132
133 def prepare_argument_spec():
134 argument_spec = {
135 "vcenter_hostname": dict(
136 type="str",
137 required=True,
138 fallback=(env_fallback, ["VMWARE_HOST"]),
139 ),
140 "vcenter_username": dict(
141 type="str",
142 required=True,
143 fallback=(env_fallback, ["VMWARE_USER"]),
144 ),
145 "vcenter_password": dict(
146 type="str",
147 required=True,
148 no_log=True,
149 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
150 ),
151 "vcenter_validate_certs": dict(
152 type="bool",
153 required=False,
154 default=True,
155 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
156 ),
157 "vcenter_rest_log_file": dict(
158 type="str",
159 required=False,
160 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
161 ),
162 "session_timeout": dict(
163 type="float",
164 required=False,
165 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
166 ),
167 }
168
169 argument_spec["vm"] = {"type": "str"}
170
171 return argument_spec
172
173
174 async def main():
175 required_if = list([])
176
177 module_args = prepare_argument_spec()
178 module = AnsibleModule(
179 argument_spec=module_args, required_if=required_if, supports_check_mode=True
180 )
181 if not module.params["vcenter_hostname"]:
182 module.fail_json("vcenter_hostname cannot be empty")
183 if not module.params["vcenter_username"]:
184 module.fail_json("vcenter_username cannot be empty")
185 if not module.params["vcenter_password"]:
186 module.fail_json("vcenter_password cannot be empty")
187 try:
188 session = await open_session(
189 vcenter_hostname=module.params["vcenter_hostname"],
190 vcenter_username=module.params["vcenter_username"],
191 vcenter_password=module.params["vcenter_password"],
192 validate_certs=module.params["vcenter_validate_certs"],
193 log_file=module.params["vcenter_rest_log_file"],
194 )
195 except Exception as err:
196 if hasattr(err, "get_message"):
197 module.fail_json(err.get_message())
198 else:
199 module.fail_json(str(err))
200 result = await entry_point(module, session)
201 module.exit_json(**result)
202
203
204 # template: info_no_list_module.j2
205 def build_url(params):
206 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/power").format(**params)
207
208
209 async def entry_point(module, session):
210 return await _info(module.params, session)
211
212
213 async def _info(params, session):
214 payload_format = list(PAYLOAD_FORMAT.values())[0]
215 _in_query_parameters = payload_format["query"].keys()
216 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/power").format(
217 **params
218 ) + gen_args(params, _in_query_parameters)
219 async with session.get(_url, **session_timeout(params)) as resp:
220 try:
221 if resp.headers["Content-Type"] == "application/json":
222 _json = await resp.json()
223 except KeyError:
224 _json = {}
225 return await update_changed_flag(_json, resp.status, "get")
226
227
228 if __name__ == "__main__":
229 import asyncio
230
231 current_loop = asyncio.new_event_loop()
232 try:
233 asyncio.set_event_loop(current_loop)
234 current_loop.run_until_complete(main())
235 finally:
236 current_loop.close()