Debian Codegraph @

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