Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Interface config #158

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Prev Previous commit
Next Next commit
Update Lint and validation functions
  • Loading branch information
kdhlab committed Jan 26, 2025
commit e35e96d077af74d1e1bf463af957c578e2a26b37
13 changes: 6 additions & 7 deletions plugins/module_utils/interfaces_configuration_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)

"""
interfaces_configuration_utils module_utils: Module_utils to configure OPNsense interface configurations
interfaces_configuration_utils module_utils: Module_utils to configure OPNsense interfaces.
"""

from dataclasses import dataclass, asdict, field
Expand Down Expand Up @@ -176,7 +176,7 @@ class InterfacesSet(OPNsenseModuleConfig):

Methods:
__init__(self, path="/conf/config.xml"): Initializes InterfacesSet and loads interfaces.
_load_interfaces() -> List["interface_configuration"]: Loads interface assignments from config.
_load_interfaces() -> List["interface_configuration"]: Loads interfaces from config.
changed() -> bool: Checks if current assignments differ from the loaded ones.
update(InterfaceConfiguration: InterfaceConfiguration): Updates an assignment,
errors if not found.
Expand Down Expand Up @@ -298,7 +298,7 @@ def add_or_update(self, interface_configuration: InterfaceConfiguration) -> None
Adds a new interface to the configuration or updates an existing one.

Args:
interface_configuration (InterfaceConfiguration): The interface configuration to add or update.
interface_configuration (InterfaceConfiguration): The interface to add or update.

Raises:
OPNSenseInterfaceNotFoundError: If the interface configuration is not found.
Expand All @@ -322,8 +322,7 @@ def add_or_update(self, interface_configuration: InterfaceConfiguration) -> None
for attr, value in interface_configuration.extra_attrs.items():
if attr == "if" and value not in device_interfaces_set:
raise OPNSenseInterfaceNotFoundError("Interface was not found on OPNsense Instance!")
else:
interface_to_update.extra_attrs[attr] = value
interface_to_update.extra_attrs[attr] = value
else:
raise OPNSenseDeviceAlreadyAssignedError("This device is already assigned, please unassign this device first")

Expand Down Expand Up @@ -358,8 +357,8 @@ def remove(self, interface_configuration: InterfaceConfiguration) -> None:
if interface_configuration in self._interfaces_configuration:
self._interfaces_configuration.remove(interface_configuration)
else:
raise OPNSenseInterfaceNotFoundError(f"Interface {interface_configuration.identifier} not found.")
raise OPNSenseInterfaceNotFoundError(f"Interface {interface_configuration.identifier} not found.")

def find(self, **kwargs) -> Optional[InterfaceConfiguration]:
"""
Searches for an interface assignment that matches given criteria.
Expand Down
33 changes: 15 additions & 18 deletions plugins/modules/interfaces_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,27 +532,17 @@ def validate_ipaddr_and_subnet(ipaddr, subnet):
if ipaddr in choices:
return ipaddr, None
try:
ip = ipaddress.ip_address(ipaddr)
if subnet is None:
raise ValueError("Subnet must be provided when ipaddr is an IP address.")
ip_network = ipaddress.ip_network(f"{ipaddr}/{subnet}", strict=False)
return ipaddr, subnet
try:
ip = ipaddress.ip_address(ipaddr)
ip_network = ipaddress.ip_network(f"{ip}/{subnet}", strict=False)
except ValueError:
raise ValueError("Invalid IPv4 Address.")
return ip, ip_network.prefixlen
except ValueError as e:
raise ValueError(f"Invalid value for ipaddr or subnet: {e}")

def validate_ipaddr6_and_subnet6(ipaddr6, subnet6):
choices = ["none", "dhcp", "pppoe"]
if ipaddr6 in choices:
return ipaddr6, None
try:
ip6 = ipaddress.ip_address(ipaddr6)
if subnet6 is None:
raise ValueError("Subnet must be provided when ipaddr6 is an IP address.")
ip_network6 = ipaddress.ip_network(f"{ipaddr6}/{subnet6}", strict=False)
return ipaddr6, subnet6
except ValueError as e:
raise ValueError(f"Invalid value for ipaddr6 or subnet6: {e}")

# Function to convert aliases to base arguments
def convert_aliases(args, alias_map):
"""
Expand Down Expand Up @@ -1013,10 +1003,17 @@ def main():

# Process the converted arguments
result = {}
if params.get("ipaddr"):
# Validate ipaddr and subnet parameters
try:
params["ipaddr"], params["subnet"] = validate_ipaddr_and_subnet(params["ipaddr6"], params["subnet6"])
except ValueError as e:
module.fail_json(msg=str(e))

if params.get("ipaddr6"):
# Validate ipaddr6 and subnet6 parameters
# Validate ipaddr and subnet parameters
try:
params["ipaddr6"], params["subnet6"] = validate_ipaddr6_and_subnet6(params["ipaddr6"], params["subnet6"])
params["ipaddr6"], params["subnet6"] = validate_ipaddr_and_subnet(params["ipaddr6"], params["subnet6"])
except ValueError as e:
module.fail_json(msg=str(e))

Expand Down
Loading