Merge pull request #4 from hatamiarash7/migrate-to-toml

Migrate to toml
This commit is contained in:
Arash Hatami 2023-04-17 16:30:01 +03:30 committed by GitHub
commit 9b41b2d3fd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 50 additions and 58 deletions

View File

@ -20,7 +20,7 @@ jobs:
- name: Install dependencies - name: Install dependencies
run: | run: |
python -m pip install --upgrade pip python -m pip install --upgrade pip
pip install pylint python-environ pip install pylint python-environ toml
- name: Analyzing the code with pylint - name: Analyzing the code with pylint
run: | run: |

3
.gitignore vendored
View File

@ -3,4 +3,5 @@
.vscode .vscode
*.conf *.conf
*.json *.json
*.toml

View File

@ -1,3 +1,9 @@
.PHONY: clean run help
.DEFAULT_GOAL := help
install: ## Install requirements
python3 -m pip install -r requirements.txt
clean: ## Clean config files clean: ## Clean config files
rm -f *.conf rm -f *.conf
@ -5,7 +11,4 @@ run: clean ## Run the script
python3 main.py python3 main.py
help: ## Show this help help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' Makefile | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' @grep -E '^[a-zA-Z_-]+:.*?## .*$$' Makefile | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
.PHONY: clean run help
.DEFAULT_GOAL := help

View File

@ -8,50 +8,36 @@ This simple script will generate tunnel config files for WireGuard.
You need to give two file contains your information: You need to give two file contains your information:
- `endpoints.json` : Contains the endpoints you want to connect to ( Name, Address ). - `endpoints.toml` : Contains the endpoints you want to connect to ( Name, Address ).
- `ip-list.json` : Contains the IP addresses you want to use. - `ip-list.toml` : Contains the IP addresses you want to use.
And also give private/other information as a `.env` file. And also give private/other information as a `.env` file.
### endpoints.json ### endpoints.toml
```json ```toml
[ Company-Server-1 = "wg-1.domain.xyz:1234"
{ Company-Server-2 = "wg-2.domain.xyz:1234"
"name": "Company-Server-1",
"address": "wg-1.domain.xyz:1234"
},
{
"name": "Company-Server-2",
"address": "wg-2.domain.xyz:1234"
}
]
``` ```
### ip-list.json ### ip-list.toml
```json ```toml
{ [k8s]
"k8s-cluster": [ DC1 = "1.2.3.4/32"
"1.2.3.4/32", DC2 = "5.6.7.8.9/32"
"5.6.7.8.9/32", DC3 = "1.2.3.4/27"
"1.2.3.4/27"
], [monitoring]
"grafana": [ prometheus = "1.2.3.4/32"
"1.2.3.4/32", grafana = "5.6.7.8.9/32"
"5.6.7.8.9/32",
"1.2.3.4/27" [other]
], server1 = "1.2.3.4/32"
"other": [ server2 = "5.6.7.8.9/32"
"1.2.3.4/32", server3 = "1.2.3.4/27"
"5.6.7.8.9/32",
"1.2.3.4/27"
]
}
``` ```
> **Note**: Array keys ( `grafana`, `other`, etc ) are not important and can be used to group IP addresses for you to read/edit better.
### .env ### .env
```env ```env

33
main.py
View File

@ -3,8 +3,8 @@ Generate WireGuard tunnel configuration files from your data
""" """
from typing import List from typing import List
import json
import environ import environ
import toml
# Load environment variables from .env file # Load environment variables from .env file
env = environ.Env() env = environ.Env()
@ -13,31 +13,32 @@ environ.Env.read_env()
def get_ips() -> List[str]: def get_ips() -> List[str]:
""" """
Load the list of IP addresses from the `ip-list.json` file Load the list of IP addresses from the `ip-list.toml` file
and return a list of unique IP addresses. and return a list of unique IP addresses.
Returns: Returns:
A list of unique IP addresses. A list of unique IP addresses.
""" """
with open('ip-list.json', 'r', encoding='UTF-8') as ip_list: with open('ip-list.toml', 'r', encoding='UTF-8') as ip_list:
ips = [] ips = []
# Load IP addresses from JSON file # Load IP addresses from TOML file
lists = json.load(ip_list) lists = toml.load(ip_list)
# Iterate over groups of IP addresses # Iterate over groups of IP addresses
for group in lists: for section in lists:
# Iterate over individual IP addresses # Iterate over individual IP addresses
for endpoint_ip in lists[group]: for endpoint_ip in lists[section]:
ips.append(endpoint_ip) ips.extend(list(lists[section][endpoint_ip].values()))
# Return a list of unique IP addresses # Return a list of unique IP addresses
return list(set(ips)) return list(set(ips))
def generate_config(profile: dict) -> None: def generate_config(endpoint: str, address: str) -> None:
""" """
Generate a WireGuard configuration file for the specified endpoint. Generate a WireGuard configuration file for the specified endpoint.
Args: Args:
profile: A dictionary containing the endpoint name and address. endpoint: The endpoint's name.
address: The endpoint's address.
Returns: Returns:
None None
@ -45,7 +46,7 @@ def generate_config(profile: dict) -> None:
# Get the list of unique IP addresses # Get the list of unique IP addresses
ips = ", ".join(map(str, get_ips())) ips = ", ".join(map(str, get_ips()))
# Define the filename for the configuration file # Define the filename for the configuration file
filename = profile['name'] + '.conf' filename = endpoint + '.conf'
# Get environment variables with default values # Get environment variables with default values
address = env('ADDRESS', default='10.0.0.1/24') address = env('ADDRESS', default='10.0.0.1/24')
mtu = env('MTU', default='1420') mtu = env('MTU', default='1420')
@ -61,19 +62,19 @@ def generate_config(profile: dict) -> None:
profile_file.write("[Peer]\n") profile_file.write("[Peer]\n")
profile_file.write(f"PublicKey = {env('PUBLIC_KEY')}\n") profile_file.write(f"PublicKey = {env('PUBLIC_KEY')}\n")
profile_file.write(f"AllowedIPs = {ips}\n") profile_file.write(f"AllowedIPs = {ips}\n")
profile_file.write(f"Endpoint = {profile['address']}\n") profile_file.write(f"Endpoint = {address}\n")
profile_file.write(f"PersistentKeepalive = {keepalive}\n") profile_file.write(f"PersistentKeepalive = {keepalive}\n")
def main(): def main():
"""The main function""" """The main function"""
# Load endpoint data from JSON file # Load endpoint data from TOML file
with open('endpoints.json', 'r', encoding='UTF-8') as endpoints_file: with open('endpoints.toml', 'r', encoding='UTF-8') as endpoints_file:
endpoints = json.load(endpoints_file) endpoints = toml.load(endpoints_file)
# Generate a configuration file for each endpoint # Generate a configuration file for each endpoint
for endpoint in endpoints: for endpoint in endpoints:
generate_config(endpoint) generate_config(endpoint, endpoints[endpoint])
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1 +1,2 @@
python-environ==0.4.54 python-environ==0.4.54
toml==0.10.2