5
|
1 import subprocess
|
|
2
|
|
3 from pyinfra import host
|
|
4 from pyinfra.facts.files import FindInFile
|
|
5 from pyinfra.operations import apt, files, systemd
|
|
6
|
|
7 # other options:
|
|
8 # https://www.reddit.com/r/WireGuard/comments/fkr240/shortest_path_between_peers/
|
|
9 # https://github.com/k4yt3x/wireguard-mesh-configurator
|
|
10 # https://github.com/mawalu/wireguard-private-networking
|
|
11 #
|
|
12
|
|
13
|
|
14 def peer_block(hostname, public_key, allowed_ips, endpoint=None, keepalive=None):
|
|
15 out = f'''\
|
|
16
|
|
17 [Peer]
|
|
18 # {hostname}
|
|
19 PublicKey = {public_key}
|
|
20 AllowedIPs = {allowed_ips}
|
|
21 '''
|
|
22 if endpoint is not None:
|
|
23 out += f'Endpoint = {endpoint}\n'
|
|
24 if keepalive is not None:
|
|
25 out += f'PersistentKeepalive = {keepalive}\n'
|
|
26 return out
|
|
27
|
|
28
|
|
29 for wireguard_interface in ['wg0', 'bogasterisk']:
|
|
30 if wireguard_interface == 'bogasterisk' and host.name != 'prime':
|
|
31 continue
|
|
32
|
|
33 # note- this is specific to the wg0 setup. Other conf files don't use it.
|
|
34 wireguard_ip = host.host_data['wireguard_address']
|
|
35
|
|
36 apt.packages(packages=['wireguard'])
|
|
37 # new pi may fail with 'Unable to access interface: Protocol not supported'. reboot fixes.
|
|
38
|
|
39 priv_key_lines = host.get_fact(FindInFile, path=f'/etc/wireguard/{wireguard_interface}.conf', pattern=r'PrivateKey.*')
|
|
40 if not priv_key_lines:
|
|
41 priv_key = subprocess.check_output(['wg', 'genkey']).strip().decode('ascii')
|
|
42 else:
|
|
43 priv_key = priv_key_lines[0].split(' = ')[1]
|
|
44
|
|
45 pub_key = subprocess.check_output(['wg', 'pubkey'], input=priv_key.encode('ascii')).strip().decode('ascii')
|
|
46 # todo: if this was new, it should be added to a file of pubkeys that peer_block can refer to
|
|
47
|
|
48 files.template(
|
12
|
49 src=f'templates/wireguard/{wireguard_interface}.conf.j2',
|
5
|
50 dest=f'/etc/wireguard/{wireguard_interface}.conf',
|
|
51 mode='600',
|
|
52 wireguard_ip=wireguard_ip,
|
|
53 priv_key=priv_key,
|
|
54 peer_block=peer_block,
|
|
55 )
|
|
56 svc = f'wg-quick@{wireguard_interface}.service'
|
|
57 files.link(path=f'/etc/systemd/system/multi-user.target.wants/{svc}', target='/lib/systemd/system/wg-quick@.service')
|
|
58
|
9
|
59 systemd.service(service=svc, daemon_reload=True, restarted=True, enabled=True)
|