Skip to content

Commit

Permalink
Add firewall_rules module (#97)
Browse files Browse the repository at this point in the history
* Init module index for firewall rule module

* Init firewall_rules doc

* Init firewall rules utils

* Init firewall rule module

* Add import sed target for local debugging

* remove findall function

* removed findall function

* added docstring to from_xml

* added docstrings to various functions

* removed comments since docstring is covering them

* fixed linter errors

* added unit test to check enum attribute not existing handling

* added docstrings for class FirewallRuleSet

* updated documentation

* added disabled handler and corresponding unit test

* added quick handle and tests

* added extended testing to test all features except log, category

* added log handle

* first draft of converge tets

* revert Makefile change

* updated the documentation

* updated documentation

* Add more molecule tests to firewall_rules

* fixed quick attribute

* fixed linter error

* added @DonGiovanni83 suggestions

* added disabled test

* Fix tests

* Introduce config contexts for config utils

* Build in config contexts for firewall utils

* Format and cleanup fw rule util tests

* Rework boolean flags for source and destination

* Init fw rule target dataclass

* Init from ansible params builder for fw rule target

* Init testing for fw rule target builder

* Add from xml to fw rule targets with tests

* Add missing test for fw rule target factory

* Add target attribute to fw rule target

* Cleanup fw rules utils

* Fix string equality check in fw rule tests

* Refactor fw rules module params

* Implement proper source & destination targets in fw rules

* Fix missing defaults in module param documentation

* Make test root a module

* Format exception message

* Fix config util test

* Finalize firewall_rule molecule tests

* Fix fw rule invert value handling

* Fix ansible module params default handling for fw rule

* Fix fw rule set delete

* Add 24.1 support for fw rule

* Update fw rule module doc

* Add fw rule target inversino test cases

* Add tests for 22.7,23.7 and fix module index

* Format changes

* Lint and cleanup firewall_rules related tests

* Format and lint firewal_rules plugins

* Introduce enum_utils for common code

* Add verbose outpur to RETRUN docs

* Make firewall_rules configure functions verbose

* Use module fqdn in molecule tests

---------

Co-authored-by: KiLLuuuhh <[email protected]>
  • Loading branch information
DonGiovanni83 and KiLLuuuhh authored Apr 17, 2024
1 parent e5bd046 commit ddc4122
Show file tree
Hide file tree
Showing 12 changed files with 3,337 additions and 47 deletions.
1,173 changes: 1,173 additions & 0 deletions molecule/firewall_rules/converge.yml

Large diffs are not rendered by default.

68 changes: 68 additions & 0 deletions molecule/firewall_rules/molecule.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
---
scenario:
name: firewall_rules
test_sequence:
# - dependency not relevant unless we have requirements
- destroy
- syntax
- create
- converge
- idempotence
- cleanup
- destroy

driver:
name: vagrant
parallel: true

platforms:
- name: "22.7"
hostname: false
box: puzzle/opnsense
box_version: "22.7"
memory: 1024
cpus: 2
instance_raw_config_args:
- 'vm.guest = :freebsd'
- 'ssh.sudo_command = "%c"'
- 'ssh.shell = "/bin/sh"'
- name: "23.1"
box: puzzle/opnsense
hostname: false
box_version: "23.1"
memory: 1024
cpus: 2
instance_raw_config_args:
- 'vm.guest = :freebsd'
- 'ssh.sudo_command = "%c"'
- 'ssh.shell = "/bin/sh"'
- name: "23.7"
box: puzzle/opnsense
hostname: false
box_version: "23.7"
memory: 1024
cpus: 2
instance_raw_config_args:
- 'vm.guest = :freebsd'
- 'ssh.sudo_command = "%c"'
- 'ssh.shell = "/bin/sh"'

- name: "24.1"
box: puzzle/opnsense
hostname: false
box_version: "24.1"
memory: 1024
cpus: 2
instance_raw_config_args:
- 'vm.guest = :freebsd'
- 'ssh.sudo_command = "%c"'
- 'ssh.shell = "/bin/sh"'

provisioner:
name: ansible
# env:
# ANSIBLE_VERBOSITY: 3
verifier:
name: ansible
options:
become: true
22 changes: 11 additions & 11 deletions plugins/module_utils/config_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ def __init__(
Args:
module_name (str): The name of the module.
check_mode (bool): Check mode
config_context_names (List[str]): Names of required config contexts.
path (str, optional): The path to the config.xml file. Defaults to "/conf/config.xml".
"""
self._module_name = module_name
Expand Down Expand Up @@ -172,22 +173,20 @@ def __exit__(self, exc_type, exc_val, exc_tb):
if self.changed and not self._check_mode:
raise RuntimeError("Config has changed. Cannot exit without saving.")

def save(self) -> bool:
def save(self, override_changed: bool = False) -> bool:
"""
Saves the config to the file if changes have been made.
Returns:
- bool: True if changes were saved, False if no changes were detected.
"""

if self.changed:
tree: ElementTree.ElementTree = ElementTree.ElementTree(
self._config_xml_tree
)
tree.write(self._config_path, encoding="utf-8", xml_declaration=True)
self._config_xml_tree = self._load_config()
return True
return False
if not self.changed and not override_changed:
return False
tree: ElementTree.ElementTree = ElementTree.ElementTree(self._config_xml_tree)
tree.write(self._config_path, encoding="utf-8", xml_declaration=True)
self._config_xml_tree = self._load_config()
return True

@property
def changed(self) -> bool:
Expand Down Expand Up @@ -296,8 +295,9 @@ def _get_configure_functions(self) -> dict:
if configure_functions is None:
raise MissingConfigDefinitionForModuleError(
f"Module '{self._module_name}' has no configure_functions defined in "
f"the ansible_collections.puzzle.opnsense.plugins.module_utils.module_index.VERSION_MAP for given " # pylint: disable=line-too-long
f"OPNsense version '{self.opnsense_version}'."
"the ansible_collections.puzzle.opnsense.plugins.module_utils."
"module_index.VERSION_MAP for given OPNsense version "
f"'{self.opnsense_version}'."
)

# ensure configure_functions are defined as a list
Expand Down
39 changes: 39 additions & 0 deletions plugins/module_utils/enum_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Copyright: (c) 2024, Puzzle ITC
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
"""Reusable Enum utilities"""
from enum import Enum
from typing import List


class ListEnum(Enum):
"""Enum class with some handy utility functions."""

@classmethod
def as_list(cls) -> List[str]:
"""
Return a list
Returns
-------
"""
return [entry.value for entry in cls]

@classmethod
def from_string(cls, value: str) -> "ListEnum":
"""
Returns Enum value, from a given String.
If no enum value can be mapped to the input string,
ValueError is raised.
Parameters
----------
value: `str`
String to be mapped to enum value
Returns
-------
Enum value
"""
for _key, _value in cls.__members__.items():
if value in (_key, _value.value):
return _value
raise ValueError(f"'{cls.__name__}' enum not found for '{value}'")
Loading

0 comments on commit ddc4122

Please sign in to comment.