diff --git a/roles/wg/tasks/generate_keypair.yml b/roles/wg/tasks/generate_keypair.yml new file mode 100644 index 0000000..8103f16 --- /dev/null +++ b/roles/wg/tasks/generate_keypair.yml @@ -0,0 +1,20 @@ +--- +- name: Generate private key + ansible.builtin.command: + cmd: wg genkey + changed_when: false + check_mode: false + register: _generated_private_key + +- name: Derive public key + ansible.builtin.command: + cmd: wg pubkey + stdin: "{{ _generated_private_key.stdout }}" + changed_when: false + check_mode: false + register: _derived_public_key + +- name: Set key/pair facts + ansible.builtin.set_fact: + wg_private_key: _generated_private_key.stdout + wg_public_key: _derived_public_key.stdout diff --git a/roles/wg/tasks/main.yml b/roles/wg/tasks/main.yml index 4f5767a..1443325 100644 --- a/roles/wg/tasks/main.yml +++ b/roles/wg/tasks/main.yml @@ -3,25 +3,36 @@ ansible.builtin.include_tasks: install.yml tags: install -- name: Generate private key - ansible.builtin.shell: - cmd: | - set -e -o pipefail - umask 077 - wg genkey | tee private.key | wg pubkey > public.key +- name: Check for existence of private key + ansible.builtin.stat: + path: /etc/wireguard/private.key + register: _private_key_stat - chdir: /etc/wireguard - creates: /etc/wireguard/private.key - when: wg_generate_keypair +- name: Generate keypair + ansible.builtin.include_tasks: tasks/generate_keypair.yml + when: not _private_key_stat.exists -- name: Get public key - ansible.builtin.command: cat /etc/wireguard/public.key - register: public_key - changed_when: False +- name: Save private key + ansible.builtin.template: + src: templates/keyfile.j2 + dest: /etc/wireguard/private.key + owner: root + group: root + mode: 0700 + vars: + key: "{{ wg_private_key }}" + when: not _private_key_stat.exists -- name: Set public key fact - ansible.builtin.set_fact: - public_key: "{{ public_key.stdout }}" +- name: Save public key + ansible.builtin.template: + src: templates/keyfile.j2 + dest: /etc/wireguard/public.key + owner: root + group: root + mode: 0700 + vars: + key: "{{ wg_public_key }}" + when: not _private_key_stat.exists - name: Set dns_command for co-openSUSE ansible.builtin.set_fact: diff --git a/roles/wg/templates/keyfile.j2 b/roles/wg/templates/keyfile.j2 new file mode 100644 index 0000000..0b65fc5 --- /dev/null +++ b/roles/wg/templates/keyfile.j2 @@ -0,0 +1 @@ +{{ key }}