Skip to content

Commit

Permalink
update utils.py to include failover-dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
superstes committed Dec 19, 2024
1 parent 0217dd8 commit 4494d22
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 4 deletions.
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,35 @@ NFTables documentation: [docs.o-x-l.com](https://docs.o-x-l.com/firewall/nftable

----

## Install

* Create directories:

```bash
mkdir -p /var/local/lib/nftables_addons /etc/nftables.d/addons/
```

* Add the script-files:

* [util.py](https://github.com/O-X-L/nftables_addon_dns/blob/latest/lib/util.py)
* [iplist.py](https://github.com/O-X-L/nftables_addon_dns/blob/latest/lib/dns.py)

* Add the config file:

`/etc/nftables.d/addons/dns.json`

* Optional: Create a service user

* Add sudoers privileges
* Allow to read lib-dir
* Allow to write to addons-config-dir

* Add cron or systemd-timer to execute the script on a schedule: `python3 /var/local/lib/nftables_addons/dns.py`

* Test it and verify it's working as expected

----

## Result

```text
Expand Down Expand Up @@ -52,7 +81,7 @@ cat /etc/nftables.d/addons/dns.nft

2. The script is executed

`python3 /usr/lib/nftables/dns.py`
`python3 /var/local/lib/nftables_addons/dns.py`

* It will load the configuration
* Resolve IPv4 and IPv6 (_if enabled_) for all configured variables
Expand Down
20 changes: 17 additions & 3 deletions lib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,14 @@
FILE_HEADER = '# Auto-Generated config - DO NOT EDIT MANUALLY!\n\n'


def format_var(name: str, data: list, version: int) -> str:
def ensure_list(data: (str, list)) -> list:
if isinstance(data, list):
return data

return [data]


def format_var(name: str, data: list, version: int, as_set: bool = True, fallback: str = None) -> str:
if version not in FALLBACK_VAR_VALUE:
version = 4

Expand All @@ -43,10 +50,17 @@ def format_var(name: str, data: list, version: int) -> str:
if append not in [None, ' ', '']:
name = f'{name}_{append}'

raw = f"define { name } = {{ %s }}"
if as_set or len(data) > 1:
raw = f"define { name } = {{ %s }}"

else:
raw = f"define { name } = %s"

if len(data) == 0:
return raw % FALLBACK_VAR_VALUE[version]
if fallback is None:
return raw % FALLBACK_VAR_VALUE[version]

return raw % fallback

return raw % ', '.join(map(str, data))

Expand Down

0 comments on commit 4494d22

Please sign in to comment.