Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_hardware_ethernet_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_hardware_ethernet_info
12 short_description: Returns information about a virtual Ethernet adapter.
13 description: Returns information about a virtual Ethernet adapter.
14 options:
15 label:
16 description:
17 - The name of the item
18 type: str
19 nic:
20 description:
21 - Virtual Ethernet adapter identifier.
22 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_ethernet).
23 Required with I(state=['get'])
24 type: str
25 session_timeout:
26 description:
27 - 'Timeout settings for client session. '
28 - 'The maximal number of seconds for the whole operation including connection
29 establishment, request sending and response. '
30 - The default value is 300s.
31 type: float
32 version_added: 2.1.0
33 vcenter_hostname:
34 description:
35 - The hostname or IP address of the vSphere vCenter
36 - If the value is not specified in the task, the value of environment variable
37 C(VMWARE_HOST) will be used instead.
38 required: true
39 type: str
40 vcenter_password:
41 description:
42 - The vSphere vCenter password
43 - If the value is not specified in the task, the value of environment variable
44 C(VMWARE_PASSWORD) will be used instead.
45 required: true
46 type: str
47 vcenter_rest_log_file:
48 description:
49 - 'You can use this optional parameter to set the location of a log file. '
50 - 'This file will be used to record the HTTP REST interaction. '
51 - 'The file will be stored on the host that runs the module. '
52 - 'If the value is not specified in the task, the value of '
53 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
54 type: str
55 vcenter_username:
56 description:
57 - The vSphere vCenter username
58 - If the value is not specified in the task, the value of environment variable
59 C(VMWARE_USER) will be used instead.
60 required: true
61 type: str
62 vcenter_validate_certs:
63 default: true
64 description:
65 - Allows connection when SSL certificates are not valid. Set to C(false) when
66 certificates are not trusted.
67 - If the value is not specified in the task, the value of environment variable
68 C(VMWARE_VALIDATE_CERTS) will be used instead.
69 type: bool
70 vm:
71 description:
72 - Virtual machine identifier.
73 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
74 This parameter is mandatory.
75 required: true
76 type: str
77 author:
78 - Ansible Cloud Team (@ansible-collections)
79 version_added: 0.1.0
80 requirements:
81 - vSphere 7.0.3 or greater
82 - python >= 3.6
83 - aiohttp
84 notes:
85 - Tested on vSphere 7.0.3
86 """
87
88 EXAMPLES = r"""
89 - name: Look up the VM called test_vm1 in the inventory
90 register: search_result
91 vmware.vmware_rest.vcenter_vm_info:
92 filter_names:
93 - test_vm1
94
95 - name: Collect information about a specific VM
96 vmware.vmware_rest.vcenter_vm_info:
97 vm: '{{ search_result.value[0].vm }}'
98 register: test_vm1_info
99
100 - name: Collect a list of the NIC for a given VM
101 vmware.vmware_rest.vcenter_vm_hardware_ethernet_info:
102 vm: '{{ test_vm1_info.id }}'
103 register: _result
104
105 - name: Collect a list of the NIC for a given VM
106 vmware.vmware_rest.vcenter_vm_hardware_ethernet_info:
107 vm: '{{ test_vm1_info.id }}'
108 register: vm_nic
109 """
110 RETURN = r"""
111 # content generated by the update_return_section callback# task: Collect a list of the NIC for a given VM
112 value:
113 description: Collect a list of the NIC for a given VM
114 returned: On success
115 sample: []
116 type: list
117 """
118
119
120 # This structure describes the format of the data expected by the end-points
121 PAYLOAD_FORMAT = {
122 "get": {"query": {}, "body": {}, "path": {"nic": "nic", "vm": "vm"}},
123 "list": {"query": {}, "body": {}, "path": {"vm": "vm"}},
124 } # pylint: disable=line-too-long
125
126 from ansible.module_utils.basic import env_fallback
127 import os
128
129 if os.getenv("VMWARE_ENABLE_TURBO", False):
130 try:
131 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
132 AnsibleTurboModule as AnsibleModule,
133 )
134
135 AnsibleModule.collection_name = "vmware.vmware_rest"
136 except ImportError:
137 from ansible.module_utils.basic import AnsibleModule
138 else:
139 from ansible.module_utils.basic import AnsibleModule
140
141 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
142 build_full_device_list,
143 exists,
144 gen_args,
145 open_session,
146 session_timeout,
147 update_changed_flag,
148 )
149
150
151 def prepare_argument_spec():
152 argument_spec = {
153 "vcenter_hostname": dict(
154 type="str",
155 required=True,
156 fallback=(env_fallback, ["VMWARE_HOST"]),
157 ),
158 "vcenter_username": dict(
159 type="str",
160 required=True,
161 fallback=(env_fallback, ["VMWARE_USER"]),
162 ),
163 "vcenter_password": dict(
164 type="str",
165 required=True,
166 no_log=True,
167 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
168 ),
169 "vcenter_validate_certs": dict(
170 type="bool",
171 required=False,
172 default=True,
173 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
174 ),
175 "vcenter_rest_log_file": dict(
176 type="str",
177 required=False,
178 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
179 ),
180 "session_timeout": dict(
181 type="float",
182 required=False,
183 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
184 ),
185 }
186
187 argument_spec["label"] = {"type": "str"}
188 argument_spec["nic"] = {"type": "str"}
189 argument_spec["vm"] = {"required": True, "type": "str"}
190
191 return argument_spec
192
193
194 async def main():
195 required_if = list([])
196
197 module_args = prepare_argument_spec()
198 module = AnsibleModule(
199 argument_spec=module_args, required_if=required_if, supports_check_mode=True
200 )
201 if not module.params["vcenter_hostname"]:
202 module.fail_json("vcenter_hostname cannot be empty")
203 if not module.params["vcenter_username"]:
204 module.fail_json("vcenter_username cannot be empty")
205 if not module.params["vcenter_password"]:
206 module.fail_json("vcenter_password cannot be empty")
207 try:
208 session = await open_session(
209 vcenter_hostname=module.params["vcenter_hostname"],
210 vcenter_username=module.params["vcenter_username"],
211 vcenter_password=module.params["vcenter_password"],
212 validate_certs=module.params["vcenter_validate_certs"],
213 log_file=module.params["vcenter_rest_log_file"],
214 )
215 except Exception as err:
216 if hasattr(err, "get_message"):
217 module.fail_json(err.get_message())
218 else:
219 module.fail_json(str(err))
220 result = await entry_point(module, session)
221 module.exit_json(**result)
222
223
224 # template: info_list_and_get_module.j2
225 def build_url(params):
226 import yarl
227
228 if params.get("nic"):
229 _in_query_parameters = PAYLOAD_FORMAT["get"]["query"].keys()
230 return yarl.URL(
231 (
232 "https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/ethernet/"
233 ).format(**params)
234 + params["nic"]
235 + gen_args(params, _in_query_parameters),
236 encoded=True,
237 )
238 _in_query_parameters = PAYLOAD_FORMAT["list"]["query"].keys()
239 return yarl.URL(
240 ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/ethernet").format(
241 **params
242 )
243 + gen_args(params, _in_query_parameters),
244 encoded=True,
245 )
246
247
248 async def entry_point(module, session):
249 url = build_url(module.params)
250 async with session.get(url, **session_timeout(module.params)) as resp:
251 _json = await resp.json()
252
253 if "value" not in _json: # 7.0.2+
254 _json = {"value": _json}
255
256 if module.params.get("nic"):
257 _json["id"] = module.params.get("nic")
258 elif module.params.get("label"): # TODO extend the list of filter
259 _json = await exists(module.params, session, str(url))
260 elif (
261 isinstance(_json["value"], list)
262 and len(_json["value"]) > 0
263 and isinstance(_json["value"][0], str)
264 ):
265 # this is a list of id, we fetch the details
266 full_device_list = await build_full_device_list(session, str(url), _json)
267 _json = {"value": [i["value"] for i in full_device_list]}
268
269 return await update_changed_flag(_json, resp.status, "get")
270
271
272 if __name__ == "__main__":
273 import asyncio
274
275 current_loop = asyncio.new_event_loop()
276 try:
277 asyncio.set_event_loop(current_loop)
278 current_loop.run_until_complete(main())
279 finally:
280 current_loop.close()