| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2016, Roman Belyakovsky <ihryamzik () gmail.com> |
| 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 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: interfaces_file |
| 11 |
short_description: Tweak settings in C(/etc/network/interfaces) files |
| 12 |
extends_documentation_fragment: |
| 13 |
- ansible.builtin.files |
| 14 |
- community.general._attributes |
| 15 |
description: |
| 16 |
- Manage (add, remove, change) individual interface options in an interfaces-style file without having to manage the file |
| 17 |
as a whole with, say, M(ansible.builtin.template) or M(ansible.builtin.assemble). Interface has to be presented in a file. |
| 18 |
- Read information about interfaces from interfaces-styled files. |
| 19 |
attributes: |
| 20 |
check_mode: |
| 21 |
support: full |
| 22 |
diff_mode: |
| 23 |
support: none |
| 24 |
options: |
| 25 |
dest: |
| 26 |
type: path |
| 27 |
description: |
| 28 |
- Path to the interfaces file. |
| 29 |
default: /etc/network/interfaces |
| 30 |
iface: |
| 31 |
type: str |
| 32 |
description: |
| 33 |
- Name of the interface, required for value changes or option remove. |
| 34 |
address_family: |
| 35 |
type: str |
| 36 |
description: |
| 37 |
- Address family of the interface, useful if same interface name is used for both V(inet) and V(inet6). |
| 38 |
option: |
| 39 |
type: str |
| 40 |
description: |
| 41 |
- Name of the option, required for value changes or option remove. |
| 42 |
value: |
| 43 |
type: str |
| 44 |
description: |
| 45 |
- If O(option) is not presented for the O(iface) and O(state) is V(present), then O(option) is added. If O(option) already |
| 46 |
exists and is not V(pre-up), V(up), V(post-up) or V(down), its value is updated. V(pre-up), V(up), V(post-up) and |
| 47 |
V(down) options cannot be updated, only adding new options, removing existing ones or cleaning the whole option set |
| 48 |
are supported. |
| 49 |
backup: |
| 50 |
description: |
| 51 |
- Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered |
| 52 |
it incorrectly. |
| 53 |
type: bool |
| 54 |
default: false |
| 55 |
state: |
| 56 |
type: str |
| 57 |
description: |
| 58 |
- If set to V(absent) the option or section is removed if present instead of created. |
| 59 |
default: "present" |
| 60 |
choices: ["present", "absent"] |
| 61 |
|
| 62 |
notes: |
| 63 |
- If option is defined multiple times last one is updated but all others are deleted in case of an O(state=absent). |
| 64 |
requirements: [] |
| 65 |
author: "Roman Belyakovsky (@hryamzik)" |
| 66 |
""" |
| 67 |
|
| 68 |
RETURN = r""" |
| 69 |
dest: |
| 70 |
description: Destination file/path. |
| 71 |
returned: success |
| 72 |
type: str |
| 73 |
sample: "/etc/network/interfaces" |
| 74 |
ifaces: |
| 75 |
description: Interfaces dictionary. |
| 76 |
returned: success |
| 77 |
type: dict |
| 78 |
contains: |
| 79 |
ifaces: |
| 80 |
description: Interface dictionary. |
| 81 |
returned: success |
| 82 |
type: dict |
| 83 |
contains: |
| 84 |
eth0: |
| 85 |
description: Name of the interface. |
| 86 |
returned: success |
| 87 |
type: dict |
| 88 |
contains: |
| 89 |
address_family: |
| 90 |
description: Interface address family. |
| 91 |
returned: success |
| 92 |
type: str |
| 93 |
sample: "inet" |
| 94 |
method: |
| 95 |
description: Interface method. |
| 96 |
returned: success |
| 97 |
type: str |
| 98 |
sample: "manual" |
| 99 |
mtu: |
| 100 |
description: Other options, all values returned as strings. |
| 101 |
returned: success |
| 102 |
type: str |
| 103 |
sample: "1500" |
| 104 |
pre-up: |
| 105 |
description: List of C(pre-up) scripts. |
| 106 |
returned: success |
| 107 |
type: list |
| 108 |
elements: str |
| 109 |
sample: |
| 110 |
- "route add -net 10.10.10.0/24 gw 10.10.10.1 dev eth1" |
| 111 |
- "route add -net 10.10.11.0/24 gw 10.10.11.1 dev eth2" |
| 112 |
up: |
| 113 |
description: List of C(up) scripts. |
| 114 |
returned: success |
| 115 |
type: list |
| 116 |
elements: str |
| 117 |
sample: |
| 118 |
- "route add -net 10.10.10.0/24 gw 10.10.10.1 dev eth1" |
| 119 |
- "route add -net 10.10.11.0/24 gw 10.10.11.1 dev eth2" |
| 120 |
post-up: |
| 121 |
description: List of C(post-up) scripts. |
| 122 |
returned: success |
| 123 |
type: list |
| 124 |
elements: str |
| 125 |
sample: |
| 126 |
- "route add -net 10.10.10.0/24 gw 10.10.10.1 dev eth1" |
| 127 |
- "route add -net 10.10.11.0/24 gw 10.10.11.1 dev eth2" |
| 128 |
down: |
| 129 |
description: List of C(down) scripts. |
| 130 |
returned: success |
| 131 |
type: list |
| 132 |
elements: str |
| 133 |
sample: |
| 134 |
- "route del -net 10.10.10.0/24 gw 10.10.10.1 dev eth1" |
| 135 |
- "route del -net 10.10.11.0/24 gw 10.10.11.1 dev eth2" |
| 136 |
""" |
| 137 |
|
| 138 |
EXAMPLES = r""" |
| 139 |
- name: Set eth1 mtu configuration value to 8000 |
| 140 |
community.general.interfaces_file: |
| 141 |
dest: /etc/network/interfaces.d/eth1.cfg |
| 142 |
iface: eth1 |
| 143 |
option: mtu |
| 144 |
value: 8000 |
| 145 |
backup: true |
| 146 |
state: present |
| 147 |
register: eth1_cfg |
| 148 |
""" |
| 149 |
|
| 150 |
import os |
| 151 |
import re |
| 152 |
import tempfile |
| 153 |
|
| 154 |
from ansible.module_utils.basic import AnsibleModule |
| 155 |
from ansible.module_utils.common.text.converters import to_bytes |
| 156 |
|
| 157 |
|
| 158 |
def lineDict(line): |
| 159 |
return {"line": line, "line_type": "unknown"} |
| 160 |
|
| 161 |
|
| 162 |
def optionDict(line, iface, option, value, address_family): |
| 163 |
return { |
| 164 |
"line": line, |
| 165 |
"iface": iface, |
| 166 |
"option": option, |
| 167 |
"value": value, |
| 168 |
"line_type": "option", |
| 169 |
"address_family": address_family, |
| 170 |
} |
| 171 |
|
| 172 |
|
| 173 |
def getValueFromLine(s): |
| 174 |
option = s.split()[0] |
| 175 |
optionStart = s.find(option) |
| 176 |
optionLen = len(option) |
| 177 |
return s[optionLen + optionStart :].strip() |
| 178 |
|
| 179 |
|
| 180 |
def read_interfaces_file(module, filename): |
| 181 |
with open(filename) as f: |
| 182 |
return read_interfaces_lines(module, f) |
| 183 |
|
| 184 |
|
| 185 |
def read_interfaces_lines(module, line_strings): |
| 186 |
lines = [] |
| 187 |
ifaces = {} |
| 188 |
currently_processing = None |
| 189 |
i = 0 |
| 190 |
for line in line_strings: |
| 191 |
i += 1 |
| 192 |
words = line.split() |
| 193 |
if len(words) < 1: |
| 194 |
lines.append(lineDict(line)) |
| 195 |
continue |
| 196 |
if words[0][0] == "#": |
| 197 |
lines.append(lineDict(line)) |
| 198 |
continue |
| 199 |
if words[0] == "mapping": |
| 200 |
# currmap = calloc(1, sizeof *currmap); |
| 201 |
lines.append(lineDict(line)) |
| 202 |
currently_processing = "MAPPING" |
| 203 |
elif words[0] == "source": |
| 204 |
lines.append(lineDict(line)) |
| 205 |
currently_processing = "NONE" |
| 206 |
elif words[0] == "source-dir": |
| 207 |
lines.append(lineDict(line)) |
| 208 |
currently_processing = "NONE" |
| 209 |
elif words[0] == "source-directory": |
| 210 |
lines.append(lineDict(line)) |
| 211 |
currently_processing = "NONE" |
| 212 |
elif words[0] == "iface": |
| 213 |
currif = {"pre-up": [], "up": [], "down": [], "post-up": []} |
| 214 |
iface_name = words[1] |
| 215 |
try: |
| 216 |
currif["address_family"] = words[2] |
| 217 |
except IndexError: |
| 218 |
currif["address_family"] = None |
| 219 |
address_family = currif["address_family"] |
| 220 |
try: |
| 221 |
currif["method"] = words[3] |
| 222 |
except IndexError: |
| 223 |
currif["method"] = None |
| 224 |
|
| 225 |
ifaces[iface_name] = currif |
| 226 |
lines.append( |
| 227 |
{ |
| 228 |
"line": line, |
| 229 |
"iface": iface_name, |
| 230 |
"line_type": "iface", |
| 231 |
"params": currif, |
| 232 |
"address_family": address_family, |
| 233 |
} |
| 234 |
) |
| 235 |
currently_processing = "IFACE" |
| 236 |
elif words[0] == "auto": |
| 237 |
lines.append(lineDict(line)) |
| 238 |
currently_processing = "NONE" |
| 239 |
elif words[0].startswith("allow-"): |
| 240 |
lines.append(lineDict(line)) |
| 241 |
currently_processing = "NONE" |
| 242 |
elif words[0] == "no-auto-down": |
| 243 |
lines.append(lineDict(line)) |
| 244 |
currently_processing = "NONE" |
| 245 |
elif words[0] == "no-scripts": |
| 246 |
lines.append(lineDict(line)) |
| 247 |
currently_processing = "NONE" |
| 248 |
else: |
| 249 |
if currently_processing == "IFACE": |
| 250 |
option_name = words[0] |
| 251 |
value = getValueFromLine(line) |
| 252 |
lines.append(optionDict(line, iface_name, option_name, value, address_family)) |
| 253 |
if option_name in ["pre-up", "up", "down", "post-up"]: |
| 254 |
currif[option_name].append(value) |
| 255 |
else: |
| 256 |
currif[option_name] = value |
| 257 |
elif currently_processing == "MAPPING": |
| 258 |
lines.append(lineDict(line)) |
| 259 |
elif currently_processing == "NONE": |
| 260 |
lines.append(lineDict(line)) |
| 261 |
else: |
| 262 |
module.fail_json(msg=f"misplaced option {line} in line {i}") |
| 263 |
return None, None |
| 264 |
return lines, ifaces |
| 265 |
|
| 266 |
|
| 267 |
def get_interface_options(iface_lines): |
| 268 |
return [i for i in iface_lines if i["line_type"] == "option"] |
| 269 |
|
| 270 |
|
| 271 |
def get_target_options(iface_options, option): |
| 272 |
return [i for i in iface_options if i["option"] == option] |
| 273 |
|
| 274 |
|
| 275 |
def update_existing_option_line(target_option, value): |
| 276 |
old_line = target_option["line"] |
| 277 |
old_value = target_option["value"] |
| 278 |
prefix_start = old_line.find(target_option["option"]) |
| 279 |
optionLen = len(target_option["option"]) |
| 280 |
old_value_position = re.search(r"\s+".join(map(re.escape, old_value.split())), old_line[prefix_start + optionLen :]) |
| 281 |
start = old_value_position.start() + prefix_start + optionLen |
| 282 |
end = old_value_position.end() + prefix_start + optionLen |
| 283 |
line = old_line[:start] + value + old_line[end:] |
| 284 |
return line |
| 285 |
|
| 286 |
|
| 287 |
def set_interface_option(module, lines, iface, option, raw_value, state, address_family=None): |
| 288 |
value = str(raw_value) |
| 289 |
changed = False |
| 290 |
|
| 291 |
iface_lines = [item for item in lines if "iface" in item and item["iface"] == iface] |
| 292 |
if address_family is not None: |
| 293 |
iface_lines = [ |
| 294 |
item for item in iface_lines if "address_family" in item and item["address_family"] == address_family |
| 295 |
] |
| 296 |
|
| 297 |
if len(iface_lines) < 1: |
| 298 |
# interface not found |
| 299 |
module.fail_json(msg=f"Error: interface {iface} not found") |
| 300 |
return changed, None |
| 301 |
|
| 302 |
iface_options = get_interface_options(iface_lines) |
| 303 |
target_options = get_target_options(iface_options, option) |
| 304 |
|
| 305 |
if state == "present": |
| 306 |
if len(target_options) < 1: |
| 307 |
changed = True |
| 308 |
# add new option |
| 309 |
last_line_dict = iface_lines[-1] |
| 310 |
changed, lines = addOptionAfterLine( |
| 311 |
option, value, iface, lines, last_line_dict, iface_options, address_family |
| 312 |
) |
| 313 |
else: |
| 314 |
if option in ["pre-up", "up", "down", "post-up"]: |
| 315 |
if len([i for i in target_options if i["value"] == value]) < 1: |
| 316 |
changed, lines = addOptionAfterLine( |
| 317 |
option, value, iface, lines, target_options[-1], iface_options, address_family |
| 318 |
) |
| 319 |
else: |
| 320 |
# if more than one option found edit the last one |
| 321 |
if target_options[-1]["value"] != value: |
| 322 |
changed = True |
| 323 |
target_option = target_options[-1] |
| 324 |
line = update_existing_option_line(target_option, value) |
| 325 |
address_family = target_option["address_family"] |
| 326 |
index = len(lines) - lines[::-1].index(target_option) - 1 |
| 327 |
lines[index] = optionDict(line, iface, option, value, address_family) |
| 328 |
elif state == "absent": |
| 329 |
if len(target_options) >= 1: |
| 330 |
if option in ["pre-up", "up", "down", "post-up"] and value is not None and value != "None": |
| 331 |
for target_option in [ito for ito in target_options if ito["value"] == value]: |
| 332 |
changed = True |
| 333 |
lines = [ln for ln in lines if ln != target_option] |
| 334 |
else: |
| 335 |
changed = True |
| 336 |
for target_option in target_options: |
| 337 |
lines = [ln for ln in lines if ln != target_option] |
| 338 |
else: |
| 339 |
module.fail_json(msg=f"Error: unsupported state {state}, has to be either present or absent") |
| 340 |
|
| 341 |
return changed, lines |
| 342 |
|
| 343 |
|
| 344 |
def addOptionAfterLine(option, value, iface, lines, last_line_dict, iface_options, address_family): |
| 345 |
# Changing method of interface is not an addition |
| 346 |
if option == "method": |
| 347 |
changed = False |
| 348 |
for ln in lines: |
| 349 |
if ( |
| 350 |
ln.get("line_type", "") == "iface" |
| 351 |
and ln.get("iface", "") == iface |
| 352 |
and value != ln.get("params", {}).get("method", "") |
| 353 |
): |
| 354 |
if address_family is not None and ln.get("address_family") != address_family: |
| 355 |
continue |
| 356 |
changed = True |
| 357 |
ln["line"] = re.sub(f"{ln.get('params', {}).get('method', '')}$", value, ln.get("line")) |
| 358 |
ln["params"]["method"] = value |
| 359 |
return changed, lines |
| 360 |
|
| 361 |
last_line = last_line_dict["line"] |
| 362 |
prefix_start = last_line.find(last_line.split()[0]) |
| 363 |
suffix_start = last_line.rfind(last_line.split()[-1]) + len(last_line.split()[-1]) |
| 364 |
prefix = last_line[:prefix_start] |
| 365 |
|
| 366 |
if len(iface_options) < 1: |
| 367 |
# interface has no options, ident |
| 368 |
prefix += " " |
| 369 |
|
| 370 |
line = f"{prefix}{option} {value}{last_line[suffix_start:]}" |
| 371 |
option_dict = optionDict(line, iface, option, value, address_family) |
| 372 |
index = len(lines) - lines[::-1].index(last_line_dict) |
| 373 |
lines.insert(index, option_dict) |
| 374 |
return True, lines |
| 375 |
|
| 376 |
|
| 377 |
def write_changes(module, lines, dest): |
| 378 |
tmpfd, tmpfile = tempfile.mkstemp() |
| 379 |
with os.fdopen(tmpfd, "wb") as f: |
| 380 |
f.write(to_bytes("".join(lines), errors="surrogate_or_strict")) |
| 381 |
module.atomic_move(tmpfile, os.path.realpath(dest)) |
| 382 |
|
| 383 |
|
| 384 |
def main(): |
| 385 |
module = AnsibleModule( |
| 386 |
argument_spec=dict( |
| 387 |
dest=dict(type="path", default="/etc/network/interfaces"), |
| 388 |
iface=dict(type="str"), |
| 389 |
address_family=dict(type="str"), |
| 390 |
option=dict(type="str"), |
| 391 |
value=dict(type="str"), |
| 392 |
backup=dict(type="bool", default=False), |
| 393 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 394 |
), |
| 395 |
add_file_common_args=True, |
| 396 |
supports_check_mode=True, |
| 397 |
required_by=dict( |
| 398 |
option=("iface",), |
| 399 |
), |
| 400 |
) |
| 401 |
|
| 402 |
dest = module.params["dest"] |
| 403 |
iface = module.params["iface"] |
| 404 |
address_family = module.params["address_family"] |
| 405 |
option = module.params["option"] |
| 406 |
value = module.params["value"] |
| 407 |
backup = module.params["backup"] |
| 408 |
state = module.params["state"] |
| 409 |
|
| 410 |
if option is not None and state == "present" and value is None: |
| 411 |
module.fail_json(msg="Value must be set if option is defined and state is 'present'") |
| 412 |
|
| 413 |
lines, ifaces = read_interfaces_file(module, dest) |
| 414 |
|
| 415 |
changed = False |
| 416 |
|
| 417 |
if option is not None: |
| 418 |
changed, lines = set_interface_option(module, lines, iface, option, value, state, address_family) |
| 419 |
|
| 420 |
if changed: |
| 421 |
dummy, ifaces = read_interfaces_lines(module, [d["line"] for d in lines if "line" in d]) |
| 422 |
|
| 423 |
if changed and not module.check_mode: |
| 424 |
if backup: |
| 425 |
module.backup_local(dest) |
| 426 |
write_changes(module, [d["line"] for d in lines if "line" in d], dest) |
| 427 |
|
| 428 |
module.exit_json(dest=dest, changed=changed, ifaces=ifaces) |
| 429 |
|
| 430 |
|
| 431 |
if __name__ == "__main__": |
| 432 |
main() |