---
- name: Gather instance facts
setup:
- include_tasks: "setup-{{ ansible_distribution|lower }}.yml"
- name: Install WireGuard
package:
name: "{{ packages }}"
state: present
vars:
packages:
- wireguard-dkms
- wireguard-tools
tags:
- wg-install
- skip_ansible_lint
- name: Enable WireGuard kernel module
modprobe:
name: wireguard
register: wireguard_module_enabled
until: wireguard_module_enabled is succeeded
retries: 10
delay: 10
failed_when: wireguard_module_enabled is failure
- name: Set WireGuard IP (without mask)
set_fact:
wireguard_ip: "{{ wireguard_address.split('/')[0] }}"
- name: Register if config/private key already exists on target host
stat:
path: "{{ wireguard_remote_directory }}/{{ wireguard_interface }}.conf"
register: config_file_stat
- wg-generate-keys
- name: Generate WireGuard private key
shell: "wg genkey"
register: wg_private_key_result
when: not config_file_stat.stat.exists
- name: Read WireGuard config file
slurp:
src: "{{ wireguard_remote_directory }}/{{ wireguard_interface }}.conf"
register: wg_config
- name: Read private key
private_key: "{{ wg_config['content'] | b64decode | regex_findall('PrivateKey = (.*)') | first }}"
wg-config
- name: Derive WireGuard public key
shell: "echo '{{ private_key }}' | wg pubkey"
register: wg_public_key_result
changed_when: false
- wg-config
- name: Set public key fact
public_key: "{{ wg_public_key_result.stdout }}"
- name: Create WireGuard configuration directory
file:
dest: "{{ wireguard_remote_directory }}"
state: directory
mode: 0700
- name: Generate WireGuard configuration file
template:
src: wg.conf.j2
dest: "{{ wireguard_remote_directory }}/{{ wireguard_interface }}.conf"
owner: root
group: root
mode: 0600
notify:
- restart wireguard
- name: check if reload-module-on-update file exists
path: "{{ wireguard_remote_directory }}/.reload-module-on-update"
register: reload_module_on_update
- name: WireGuard reload-module-on-update
dest: "{{ wireguard_remote_directory }}/.reload-module-on-update"
state: touch
when: not reload_module_on_update.stat.exists
- name: Start and enable WireGuard service
service:
name: "wg-quick@{{ wireguard_interface }}"
state: started
enabled: yes
- name: Delete local cert directory
path: "{{ wireguard_cert_directory }}"
state: absent
delegate_to: localhost
run_once: true