Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox_nic.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2021, Lammert Hellinga (@Kogelvis) <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7
8 DOCUMENTATION = r"""
9 module: proxmox_nic
10 short_description: Management of a NIC of a Qemu(KVM) VM in a Proxmox VE cluster
11 description:
12 - Allows you to create/update/delete a NIC on Qemu(KVM) Virtual Machines in a Proxmox VE cluster.
13 author: "Lammert Hellinga (@Kogelvis) <[email protected]>"
14 attributes:
15 check_mode:
16 support: full
17 diff_mode:
18 support: none
19 options:
20 bridge:
21 description:
22 - Add this interface to the specified bridge device. The Proxmox VE default bridge is called V(vmbr0).
23 type: str
24 firewall:
25 description:
26 - Whether this interface should be protected by the firewall.
27 type: bool
28 default: false
29 interface:
30 description:
31 - Name of the interface, should be V(net[n]) where C(0 ≤ n ≤ 31).
32 type: str
33 required: true
34 link_down:
35 description:
36 - Whether this interface should be disconnected (like pulling the plug).
37 type: bool
38 default: false
39 mac:
40 description:
41 - V(XX:XX:XX:XX:XX:XX) should be a unique MAC address. This is automatically generated if not specified.
42 - When not specified this module will keep the MAC address the same when changing an existing interface.
43 type: str
44 model:
45 description:
46 - The NIC emulator model.
47 type: str
48 choices: ['e1000', 'e1000-82540em', 'e1000-82544gc', 'e1000-82545em', 'i82551', 'i82557b', 'i82559er', 'ne2k_isa', 'ne2k_pci',
49 'pcnet', 'rtl8139', 'virtio', 'vmxnet3']
50 default: virtio
51 mtu:
52 description:
53 - Force MTU, for C(virtio) model only, setting will be ignored otherwise.
54 - Set to V(1) to use the bridge MTU.
55 - Value should be C(1 ≤ n ≤ 65520).
56 type: int
57 name:
58 description:
59 - Specifies the VM name. Only used on the configuration web interface.
60 - Required only for O(state=present).
61 type: str
62 queues:
63 description:
64 - Number of packet queues to be used on the device.
65 - Value should be C(0 ≤ n ≤ 16).
66 type: int
67 rate:
68 description:
69 - Rate limit in MBps (MegaBytes per second) as floating point number.
70 type: float
71 state:
72 description:
73 - Indicates desired state of the NIC.
74 type: str
75 choices: ['present', 'absent']
76 default: present
77 tag:
78 description:
79 - VLAN tag to apply to packets on this interface.
80 - Value should be C(1 ≤ n ≤ 4094).
81 type: int
82 trunks:
83 description:
84 - List of VLAN trunks to pass through this interface.
85 type: list
86 elements: int
87 vmid:
88 description:
89 - Specifies the instance ID.
90 type: int
91 extends_documentation_fragment:
92 - community.proxmox.proxmox.actiongroup_proxmox
93 - community.proxmox.proxmox.documentation
94 - community.proxmox.attributes
95 """
96
97 EXAMPLES = r"""
98 - name: Create NIC net0 targeting the vm by name
99 community.proxmox.proxmox_nic:
100 name: my_vm
101 interface: net0
102 bridge: vmbr0
103 tag: 3
104
105 - name: Create NIC net0 targeting the vm by id
106 community.proxmox.proxmox_nic:
107 vmid: 103
108 interface: net0
109 bridge: vmbr0
110 mac: "12:34:56:C0:FF:EE"
111 firewall: true
112
113 - name: Delete NIC net0 targeting the vm by name
114 community.proxmox.proxmox_nic:
115 name: my_vm
116 interface: net0
117 state: absent
118 """
119
120 RETURN = r"""
121 vmid:
122 description: The VM vmid.
123 returned: success
124 type: int
125 sample: 115
126 msg:
127 description: A short message.
128 returned: always
129 type: str
130 sample: "Nic net0 unchanged on VM with vmid 103"
131 """
132
133 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
134 ProxmoxAnsible,
135 create_proxmox_module,
136 )
137
138
139 def module_args():
140 return dict(
141 bridge=dict(type="str"),
142 firewall=dict(type="bool", default=False),
143 interface=dict(type="str", required=True),
144 link_down=dict(type="bool", default=False),
145 mac=dict(type="str"),
146 model=dict(
147 choices=[
148 "e1000",
149 "e1000-82540em",
150 "e1000-82544gc",
151 "e1000-82545em",
152 "i82551",
153 "i82557b",
154 "i82559er",
155 "ne2k_isa",
156 "ne2k_pci",
157 "pcnet",
158 "rtl8139",
159 "virtio",
160 "vmxnet3",
161 ],
162 default="virtio",
163 ),
164 mtu=dict(type="int"),
165 name=dict(type="str"),
166 queues=dict(type="int"),
167 rate=dict(type="float"),
168 state=dict(default="present", choices=["present", "absent"]),
169 tag=dict(type="int"),
170 trunks=dict(type="list", elements="int"),
171 vmid=dict(type="int"),
172 )
173
174
175 def module_options():
176 return dict(required_one_of=[("name", "vmid")])
177
178
179 class ProxmoxNicAnsible(ProxmoxAnsible):
180 def update_nic(self, vmid, interface, model, **kwargs): # noqa: PLR0912
181 vm = self.get_vm(vmid)
182
183 try:
184 vminfo = self.proxmox_api.nodes(vm["node"]).qemu(vmid).config.get()
185 except Exception as e:
186 self.module.fail_json(msg=f"Getting information for VM with vmid = {vmid} failed with exception: {e}")
187
188 if interface in vminfo:
189 # Convert the current config to a dictionary
190 config = vminfo[interface].split(",")
191 config.sort()
192
193 config_current = {}
194
195 for i in config:
196 kv = i.split("=")
197 try:
198 config_current[kv[0]] = kv[1]
199 except IndexError:
200 config_current[kv[0]] = ""
201
202 # determine the current model nic and mac-address
203 models = [
204 "e1000",
205 "e1000-82540em",
206 "e1000-82544gc",
207 "e1000-82545em",
208 "i82551",
209 "i82557b",
210 "i82559er",
211 "ne2k_isa",
212 "ne2k_pci",
213 "pcnet",
214 "rtl8139",
215 "virtio",
216 "vmxnet3",
217 ]
218 current_model = set(models) & set(config_current.keys())
219 current_model = current_model.pop()
220 current_mac = config_current[current_model]
221
222 # build nic config string
223 config_provided = f"{model}={current_mac}"
224 else:
225 config_provided = model
226
227 if kwargs["mac"]:
228 config_provided = f"{model}={kwargs['mac']}"
229
230 if kwargs["bridge"]:
231 config_provided += f",bridge={kwargs['bridge']}"
232
233 if kwargs["firewall"]:
234 config_provided += ",firewall=1"
235
236 if kwargs["link_down"]:
237 config_provided += ",link_down=1"
238
239 if kwargs["mtu"]:
240 config_provided += f",mtu={kwargs['mtu']}"
241 if model != "virtio":
242 self.module.warn(
243 f"Ignoring MTU for nic {interface} on VM with vmid {vmid}, model should be set to 'virtio': "
244 )
245
246 if kwargs["queues"]:
247 config_provided += f",queues={kwargs['queues']}"
248
249 if kwargs["rate"]:
250 config_provided += f",rate={kwargs['rate']}"
251
252 if kwargs["tag"]:
253 config_provided += f",tag={kwargs['tag']}"
254
255 if kwargs["trunks"]:
256 config_provided += f",trunks={';'.join(str(x) for x in kwargs['trunks'])}"
257
258 net = {interface: config_provided}
259 vm = self.get_vm(vmid)
260
261 if (interface not in vminfo) or (vminfo[interface] != config_provided):
262 if not self.module.check_mode:
263 self.proxmox_api.nodes(vm["node"]).qemu(vmid).config.set(**net)
264 return True
265
266 return False
267
268 def delete_nic(self, vmid, interface):
269 vm = self.get_vm(vmid)
270 vminfo = self.proxmox_api.nodes(vm["node"]).qemu(vmid).config.get()
271
272 if interface in vminfo:
273 if not self.module.check_mode:
274 self.proxmox_api.nodes(vm["node"]).qemu(vmid).config.set(delete=interface)
275 return True
276
277 return False
278
279
280 def main():
281 module = create_proxmox_module(module_args(), **module_options())
282 proxmox = ProxmoxNicAnsible(module)
283
284 interface = module.params["interface"]
285 model = module.params["model"]
286 name = module.params["name"]
287 state = module.params["state"]
288 vmid = module.params["vmid"]
289
290 # If vmid is not defined then retrieve its value from the vm name,
291 if not vmid:
292 vmid = proxmox.get_vmid(name)
293
294 # Ensure VM id exists
295 proxmox.get_vm(vmid)
296
297 if state == "present":
298 try:
299 if proxmox.update_nic(
300 vmid,
301 interface,
302 model,
303 bridge=module.params["bridge"],
304 firewall=module.params["firewall"],
305 link_down=module.params["link_down"],
306 mac=module.params["mac"],
307 mtu=module.params["mtu"],
308 queues=module.params["queues"],
309 rate=module.params["rate"],
310 tag=module.params["tag"],
311 trunks=module.params["trunks"],
312 ):
313 module.exit_json(changed=True, vmid=vmid, msg=f"Nic {interface} updated on VM with vmid {vmid}")
314 else:
315 module.exit_json(vmid=vmid, msg=f"Nic {interface} unchanged on VM with vmid {vmid}")
316 except Exception as e:
317 module.fail_json(vmid=vmid, msg=f"Unable to change nic {interface} on VM with vmid {vmid}: " + str(e))
318
319 elif state == "absent":
320 try:
321 if proxmox.delete_nic(vmid, interface):
322 module.exit_json(changed=True, vmid=vmid, msg=f"Nic {interface} deleted on VM with vmid {vmid}")
323 else:
324 module.exit_json(vmid=vmid, msg=f"Nic {interface} does not exist on VM with vmid {vmid}")
325 except Exception as e:
326 module.fail_json(vmid=vmid, msg=f"Unable to delete nic {interface} on VM with vmid {vmid}: " + str(e))
327
328
329 if __name__ == "__main__":
330 main()