Debian Codegraph @

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