Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_networking.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
12 short_description: Reset and restarts network configuration on all interfaces, also
13 this will renew the DHCP lease for DHCP IP address.
14 description: Reset and restarts network configuration on all interfaces, also this
15 will renew the DHCP lease for DHCP IP address.
16 options:
17 ipv6_enabled:
18 description:
19 - IPv6 Enabled or not
20 - If unspecified, leaves the current state of Ipv6.
21 type: bool
22 session_timeout:
23 description:
24 - 'Timeout settings for client session. '
25 - 'The maximal number of seconds for the whole operation including connection
26 establishment, request sending and response. '
27 - The default value is 300s.
28 type: float
29 version_added: 2.1.0
30 state:
31 choices:
32 - present
33 - reset
34 default: present
35 description: []
36 type: str
37 vcenter_hostname:
38 description:
39 - The hostname or IP address of the vSphere vCenter
40 - If the value is not specified in the task, the value of environment variable
41 C(VMWARE_HOST) will be used instead.
42 required: true
43 type: str
44 vcenter_password:
45 description:
46 - The vSphere vCenter password
47 - If the value is not specified in the task, the value of environment variable
48 C(VMWARE_PASSWORD) will be used instead.
49 required: true
50 type: str
51 vcenter_rest_log_file:
52 description:
53 - 'You can use this optional parameter to set the location of a log file. '
54 - 'This file will be used to record the HTTP REST interaction. '
55 - 'The file will be stored on the host that runs the module. '
56 - 'If the value is not specified in the task, the value of '
57 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
58 type: str
59 vcenter_username:
60 description:
61 - The vSphere vCenter username
62 - If the value is not specified in the task, the value of environment variable
63 C(VMWARE_USER) will be used instead.
64 required: true
65 type: str
66 vcenter_validate_certs:
67 default: true
68 description:
69 - Allows connection when SSL certificates are not valid. Set to C(false) when
70 certificates are not trusted.
71 - If the value is not specified in the task, the value of environment variable
72 C(VMWARE_VALIDATE_CERTS) will be used instead.
73 type: bool
74 author:
75 - Ansible Cloud Team (@ansible-collections)
76 version_added: 2.0.0
77 requirements:
78 - vSphere 7.0.3 or greater
79 - python >= 3.6
80 - aiohttp
81 notes:
82 - Tested on vSphere 7.0.3
83 """
84
85 EXAMPLES = r"""
86 - name: Set network information
87 vmware.vmware_rest.appliance_networking:
88 ipv6_enabled: false
89 register: result
90 """
91 RETURN = r"""
92 # content generated by the update_return_section callback# task: Set network information
93 id:
94 description: moid of the resource
95 returned: On success
96 sample: null
97 type: dict
98 value:
99 description: Set network information
100 returned: On success
101 sample: {}
102 type: dict
103 """
104
105
106 # This structure describes the format of the data expected by the end-points
107 PAYLOAD_FORMAT = {
108 "reset": {"query": {}, "body": {}, "path": {}},
109 "update": {"query": {}, "body": {"ipv6_enabled": "ipv6_enabled"}, "path": {}},
110 } # pylint: disable=line-too-long
111
112 from ansible.module_utils.basic import env_fallback
113 import os
114
115 if os.getenv("VMWARE_ENABLE_TURBO", False):
116 try:
117 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
118 AnsibleTurboModule as AnsibleModule,
119 )
120
121 AnsibleModule.collection_name = "vmware.vmware_rest"
122 except ImportError:
123 from ansible.module_utils.basic import AnsibleModule
124 else:
125 from ansible.module_utils.basic import AnsibleModule
126
127 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
128 exists,
129 gen_args,
130 get_subdevice_type,
131 open_session,
132 prepare_payload,
133 session_timeout,
134 update_changed_flag,
135 )
136
137
138 def prepare_argument_spec():
139 argument_spec = {
140 "vcenter_hostname": dict(
141 type="str",
142 required=True,
143 fallback=(env_fallback, ["VMWARE_HOST"]),
144 ),
145 "vcenter_username": dict(
146 type="str",
147 required=True,
148 fallback=(env_fallback, ["VMWARE_USER"]),
149 ),
150 "vcenter_password": dict(
151 type="str",
152 required=True,
153 no_log=True,
154 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
155 ),
156 "vcenter_validate_certs": dict(
157 type="bool",
158 required=False,
159 default=True,
160 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
161 ),
162 "vcenter_rest_log_file": dict(
163 type="str",
164 required=False,
165 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
166 ),
167 "session_timeout": dict(
168 type="float",
169 required=False,
170 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
171 ),
172 }
173
174 argument_spec["ipv6_enabled"] = {"type": "bool"}
175 argument_spec["state"] = {
176 "type": "str",
177 "choices": ["present", "reset"],
178 "default": "present",
179 }
180
181 return argument_spec
182
183
184 async def main():
185 required_if = list([])
186
187 module_args = prepare_argument_spec()
188 module = AnsibleModule(
189 argument_spec=module_args, required_if=required_if, supports_check_mode=False
190 )
191 if not module.params["vcenter_hostname"]:
192 module.fail_json("vcenter_hostname cannot be empty")
193 if not module.params["vcenter_username"]:
194 module.fail_json("vcenter_username cannot be empty")
195 if not module.params["vcenter_password"]:
196 module.fail_json("vcenter_password cannot be empty")
197 try:
198 session = await open_session(
199 vcenter_hostname=module.params["vcenter_hostname"],
200 vcenter_username=module.params["vcenter_username"],
201 vcenter_password=module.params["vcenter_password"],
202 validate_certs=module.params["vcenter_validate_certs"],
203 log_file=module.params["vcenter_rest_log_file"],
204 )
205 except Exception as err:
206 if hasattr(err, "get_message"):
207 module.fail_json(err.get_message())
208 else:
209 module.fail_json(str(err))
210 result = await entry_point(module, session)
211 module.exit_json(**result)
212
213
214 # template: default_module.j2
215 def build_url(params):
216 return ("https://{vcenter_hostname}" "/api/appliance/networking").format(**params)
217
218
219 async def entry_point(module, session):
220
221 if module.params["state"] == "present":
222 if "_create" in globals():
223 operation = "create"
224 else:
225 operation = "update"
226 elif module.params["state"] == "absent":
227 operation = "delete"
228 else:
229 operation = module.params["state"]
230
231 func = globals()["_" + operation]
232
233 return await func(module.params, session)
234
235
236 async def _reset(params, session):
237 _in_query_parameters = PAYLOAD_FORMAT["reset"]["query"].keys()
238 payload = prepare_payload(params, PAYLOAD_FORMAT["reset"])
239 subdevice_type = get_subdevice_type("/api/appliance/networking?action=reset")
240 if subdevice_type and not params[subdevice_type]:
241 _json = await exists(params, session, build_url(params))
242 if _json:
243 params[subdevice_type] = _json["id"]
244 _url = (
245 "https://{vcenter_hostname}"
246 # aa
247 "/api/appliance/networking?action=reset"
248 ).format(**params) + gen_args(params, _in_query_parameters)
249 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
250 try:
251 if resp.headers["Content-Type"] == "application/json":
252 _json = await resp.json()
253 except KeyError:
254 _json = {}
255 if "value" not in _json: # 7.0.2
256 _json = {"value": _json}
257
258 return await update_changed_flag(_json, resp.status, "reset")
259
260
261 async def _update(params, session):
262 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
263 _url = ("https://{vcenter_hostname}" "/api/appliance/networking").format(**params)
264 async with session.get(_url, **session_timeout(params)) as resp:
265 _json = await resp.json()
266 if "value" in _json:
267 value = _json["value"]
268 else: # 7.0.2 and greater
269 value = _json
270 for k, v in value.items():
271 if k in payload:
272 if isinstance(payload[k], dict) and isinstance(v, dict):
273 to_delete = True
274 for _k in list(payload[k].keys()):
275 if payload[k][_k] != v.get(_k):
276 to_delete = False
277 if to_delete:
278 del payload[k]
279 elif payload[k] == v:
280 del payload[k]
281 elif payload[k] == {}:
282 del payload[k]
283
284 if payload == {} or payload == {"spec": {}}:
285 # Nothing has changed
286 if "value" not in _json: # 7.0.2
287 _json = {"value": _json}
288 _json["id"] = params.get("None")
289 return await update_changed_flag(_json, resp.status, "get")
290 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
291 try:
292 if resp.headers["Content-Type"] == "application/json":
293 _json = await resp.json()
294 except KeyError:
295 _json = {}
296 if "value" not in _json: # 7.0.2
297 _json = {"value": _json}
298
299 # e.g: content_configuration
300 if not _json and resp.status == 204:
301 async with session.get(_url, **session_timeout(params)) as resp_get:
302 _json_get = await resp_get.json()
303 if _json_get:
304 _json = _json_get
305
306 _json["id"] = params.get("None")
307 return await update_changed_flag(_json, resp.status, "update")
308
309
310 if __name__ == "__main__":
311 import asyncio
312
313 current_loop = asyncio.new_event_loop()
314 try:
315 asyncio.set_event_loop(current_loop)
316 current_loop.run_until_complete(main())
317 finally:
318 current_loop.close()