Skip to content

Instantly share code, notes, and snippets.

@corny
Last active October 21, 2020 06:50
Show Gist options
  • Save corny/aeed3c953261dfbe62bc8a578f55dd1a to your computer and use it in GitHub Desktop.
Save corny/aeed3c953261dfbe62bc8a578f55dd1a to your computer and use it in GitHub Desktop.
Ansible module to read or generate a WireGuard keypair
#!/usr/bin/python
EXAMPLES = '''
# Reads or generates a wireguard key
- wg_key: path=/etc/wireguard/site/secret.conf
'''
from ansible.module_utils.basic import AnsibleModule
import os
import re
import subprocess
if __name__ == '__main__':
module = AnsibleModule(
argument_spec={
'path': {'required': True, 'type': 'str'},
}
)
path = module.params['path']
pattern = re.compile(r'^PrivateKey\s*=\s*(\S+)')
facts = None
privkey = None
if os.path.isfile(path):
# Extract private key
for line in open(path):
m = re.match(pattern, line)
if m:
privkey = m.group(1).encode()
break
else:
# Generate private key
privkey = subprocess.check_output(["wg", "genkey"]).strip()
if privkey:
facts = {
"wg_privkey": privkey,
# Derive public key from private key
"wg_pubkey": subprocess.check_output(["wg", "pubkey"], input=privkey).strip(),
}
module.exit_json(ansible_facts=facts)
else:
module.fail_json(msg="Unable to find/generate wireguard key")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment