Debian Codegraph @

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