From cf02110610705d7e790cad300562fd3fe467d8da Mon Sep 17 00:00:00 2001 From: Robert Kaussow Date: Tue, 11 Oct 2022 09:32:13 +0200 Subject: [PATCH] initial commit --- .drone.jsonnet | 159 ++++++++++++++++++++++++++ .drone.yml | 152 ++++++++++++++++++++++++ .gitignore | 11 ++ .later.yml | 19 +++ .prettierignore | 1 + LICENSE | 21 ++++ README.md | 10 ++ defaults/main.yml | 14 +++ handlers/main.yml | 10 ++ meta/main.yml | 23 ++++ molecule/default | 1 + molecule/pytest.ini | 3 + molecule/requirements.yml | 6 + molecule/rocky9/converge.yml | 5 + molecule/rocky9/create.yml | 120 +++++++++++++++++++ molecule/rocky9/destroy.yml | 78 +++++++++++++ molecule/rocky9/molecule.yml | 24 ++++ molecule/rocky9/prepare.yml | 15 +++ molecule/rocky9/tests/test_default.py | 13 +++ setup.cfg | 12 ++ tasks/main.yml | 79 +++++++++++++ templates/etc/wireguard/wg.conf.j2 | 80 +++++++++++++ 22 files changed, 856 insertions(+) create mode 100644 .drone.jsonnet create mode 100644 .drone.yml create mode 100644 .gitignore create mode 100644 .later.yml create mode 100644 .prettierignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 defaults/main.yml create mode 100644 handlers/main.yml create mode 100644 meta/main.yml create mode 120000 molecule/default create mode 100644 molecule/pytest.ini create mode 100644 molecule/requirements.yml create mode 100644 molecule/rocky9/converge.yml create mode 100644 molecule/rocky9/create.yml create mode 100644 molecule/rocky9/destroy.yml create mode 100644 molecule/rocky9/molecule.yml create mode 100644 molecule/rocky9/prepare.yml create mode 100644 molecule/rocky9/tests/test_default.py create mode 100644 setup.cfg create mode 100644 tasks/main.yml create mode 100644 templates/etc/wireguard/wg.conf.j2 diff --git a/.drone.jsonnet b/.drone.jsonnet new file mode 100644 index 0000000..871a17f --- /dev/null +++ b/.drone.jsonnet @@ -0,0 +1,159 @@ +local PipelineLinting = { + kind: 'pipeline', + name: 'linting', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + name: 'ansible-later', + image: 'thegeeklab/ansible-later', + commands: [ + 'ansible-later', + ], + }, + { + name: 'python-format', + image: 'python:3.9', + environment: { + PY_COLORS: 1, + }, + commands: [ + 'pip install -qq yapf', + '[ ! -z "$(find . -type f -name *.py)" ] && yapf -rd ./', + ], + }, + { + name: 'python-flake8', + image: 'python:3.9', + environment: { + PY_COLORS: 1, + }, + commands: [ + 'pip install -qq flake8', + 'flake8', + ], + }, + ], + trigger: { + ref: ['refs/heads/main', 'refs/tags/**', 'refs/pull/**'], + }, +}; + +local PipelineDeployment(scenario='rocky9') = { + kind: 'pipeline', + name: 'testing-' + scenario, + platform: { + os: 'linux', + arch: 'amd64', + }, + concurrency: { + limit: 1, + }, + workspace: { + base: '/drone/src', + path: '${DRONE_REPO_NAME}', + }, + steps: [ + { + name: 'ansible-molecule', + image: 'thegeeklab/molecule:3', + environment: { + HCLOUD_TOKEN: { from_secret: 'hcloud_token' }, + }, + commands: [ + 'molecule test -s ' + scenario, + ], + }, + ], + depends_on: [ + 'linting', + ], + trigger: { + ref: ['refs/heads/main', 'refs/tags/**'], + }, +}; + +local PipelineDocumentation = { + kind: 'pipeline', + name: 'documentation', + platform: { + os: 'linux', + arch: 'amd64', + }, + steps: [ + { + name: 'generate', + image: 'thegeeklab/ansible-doctor', + environment: { + ANSIBLE_DOCTOR_LOG_LEVEL: 'INFO', + ANSIBLE_DOCTOR_FORCE_OVERWRITE: true, + ANSIBLE_DOCTOR_EXCLUDE_FILES: 'molecule/', + ANSIBLE_DOCTOR_TEMPLATE: 'hugo-book', + ANSIBLE_DOCTOR_ROLE_NAME: '${DRONE_REPO_NAME#*.}', + ANSIBLE_DOCTOR_OUTPUT_DIR: '_docs/', + }, + }, + { + name: 'publish', + image: 'plugins/gh-pages', + settings: { + remote_url: 'https://gitea.rknet.org/ansible/${DRONE_REPO_NAME}', + netrc_machine: 'gitea.rknet.org', + username: { from_secret: 'gitea_username' }, + password: { from_secret: 'gitea_token' }, + pages_directory: '_docs/', + target_branch: 'docs', + }, + when: { + ref: ['refs/heads/main'], + }, + }, + ], + trigger: { + ref: ['refs/heads/main', 'refs/tags/**', 'refs/pull/**'], + }, + depends_on: [ + 'testing-rocky9', + ], +}; + +local PipelineNotification = { + kind: 'pipeline', + name: 'notification', + platform: { + os: 'linux', + arch: 'amd64', + }, + clone: { + disable: true, + }, + steps: [ + { + name: 'matrix', + image: 'thegeeklab/drone-matrix', + settings: { + homeserver: { from_secret: 'matrix_homeserver' }, + roomid: { from_secret: 'matrix_roomid' }, + template: 'Status: **{{ build.Status }}**
Build: [{{ repo.Owner }}/{{ repo.Name }}]({{ build.Link }}){{#if build.Branch}} ({{ build.Branch }}){{/if}} by {{ commit.Author }}
Message: {{ commit.Message.Title }}', + username: { from_secret: 'matrix_username' }, + password: { from_secret: 'matrix_password' }, + }, + }, + ], + depends_on: [ + 'documentation', + ], + trigger: { + status: ['success', 'failure'], + ref: ['refs/heads/main', 'refs/tags/**'], + }, +}; + +[ + PipelineLinting, + PipelineDeployment(scenario='rocky9'), + PipelineDocumentation, + PipelineNotification, +] diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..ed0de7b --- /dev/null +++ b/.drone.yml @@ -0,0 +1,152 @@ +--- +kind: pipeline +name: linting + +platform: + os: linux + arch: amd64 + +steps: + - name: ansible-later + image: thegeeklab/ansible-later + commands: + - ansible-later + + - name: python-format + image: python:3.9 + commands: + - pip install -qq yapf + - "[ ! -z \"$(find . -type f -name *.py)\" ] && yapf -rd ./" + environment: + PY_COLORS: 1 + + - name: python-flake8 + image: python:3.9 + commands: + - pip install -qq flake8 + - flake8 + environment: + PY_COLORS: 1 + +trigger: + ref: + - refs/heads/main + - refs/tags/** + - refs/pull/** + +--- +kind: pipeline +name: testing-rocky9 + +platform: + os: linux + arch: amd64 + +concurrency: + limit: 1 + +workspace: + base: /drone/src + path: ${DRONE_REPO_NAME} + +steps: + - name: ansible-molecule + image: thegeeklab/molecule:3 + commands: + - molecule test -s rocky9 + environment: + HCLOUD_TOKEN: + from_secret: hcloud_token + +trigger: + ref: + - refs/heads/main + - refs/tags/** + +depends_on: + - linting + +--- +kind: pipeline +name: documentation + +platform: + os: linux + arch: amd64 + +steps: + - name: generate + image: thegeeklab/ansible-doctor + environment: + ANSIBLE_DOCTOR_EXCLUDE_FILES: molecule/ + ANSIBLE_DOCTOR_FORCE_OVERWRITE: true + ANSIBLE_DOCTOR_LOG_LEVEL: INFO + ANSIBLE_DOCTOR_OUTPUT_DIR: _docs/ + ANSIBLE_DOCTOR_ROLE_NAME: ${DRONE_REPO_NAME#*.} + ANSIBLE_DOCTOR_TEMPLATE: hugo-book + + - name: publish + image: plugins/gh-pages + settings: + netrc_machine: gitea.rknet.org + pages_directory: _docs/ + password: + from_secret: gitea_token + remote_url: https://gitea.rknet.org/ansible/${DRONE_REPO_NAME} + target_branch: docs + username: + from_secret: gitea_username + when: + ref: + - refs/heads/main + +trigger: + ref: + - refs/heads/main + - refs/tags/** + - refs/pull/** + +depends_on: + - testing-rocky9 + +--- +kind: pipeline +name: notification + +platform: + os: linux + arch: amd64 + +clone: + disable: true + +steps: + - name: matrix + image: thegeeklab/drone-matrix + settings: + homeserver: + from_secret: matrix_homeserver + password: + from_secret: matrix_password + roomid: + from_secret: matrix_roomid + template: "Status: **{{ build.Status }}**
Build: [{{ repo.Owner }}/{{ repo.Name }}]({{ build.Link }}){{#if build.Branch}} ({{ build.Branch }}){{/if}} by {{ commit.Author }}
Message: {{ commit.Message.Title }}" + username: + from_secret: matrix_username + +trigger: + ref: + - refs/heads/main + - refs/tags/** + status: + - success + - failure + +depends_on: + - documentation + +--- +kind: signature +hmac: edad4549be885f935b843f83c052815ec8ac7f7264a8305e78eadef38dd7feb2 + +... diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d97b7cd --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# ---> Ansible +*.retry +plugins +library + +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + diff --git a/.later.yml b/.later.yml new file mode 100644 index 0000000..0efe5d5 --- /dev/null +++ b/.later.yml @@ -0,0 +1,19 @@ +--- +ansible: + custom_modules: + - iptables_raw + - openssl_pkcs12 + - proxmox_kvm + - ucr + - corenetworks_dns + - corenetworks_token + +rules: + exclude_files: + - molecule/ + - "LICENSE*" + - "**/*.md" + - "**/*.ini" + + exclude_filter: + - LINT0009 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..ef05acb --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +.drone* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3812eb4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Robert Kaussow + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice (including the next +paragraph) shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF +OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d58ce05 --- /dev/null +++ b/README.md @@ -0,0 +1,10 @@ +# xoxys.wireguard + +[![Build Status](https://img.shields.io/drone/build/ansible/xoxys.wireguard?logo=drone&server=https%3A%2F%2Fdrone.rknet.org)](https://drone.rknet.org/ansible/xoxys.wireguard) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?label=license)](LICENSE) + +Setup wireguard VPN. You can find the full documentation at [https://galaxy.geekdocs.de](https://galaxy.geekdocs.de/roles/security/wireguard/). + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. diff --git a/defaults/main.yml b/defaults/main.yml new file mode 100644 index 0000000..3334cce --- /dev/null +++ b/defaults/main.yml @@ -0,0 +1,14 @@ +--- +wireguard_address: "10.0.0.1/24" + +# @var:wireguard_port: The default port WireGuard will listen if not specified otherwise. +wireguard_port: "51820" + +# The default interface name that WireGuard should use if not specified otherwise. +wireguard_interface: "wg0" + +# @var:wireguard_private_key: Private key to use. If not private key is given, the role will auto-generate a new key. +# @var:wireguard_private_key:default: $ "_unset_" + +wireguard_peers: [] +wireguard_peers_unmanaged: [] diff --git a/handlers/main.yml b/handlers/main.yml new file mode 100644 index 0000000..dd00bad --- /dev/null +++ b/handlers/main.yml @@ -0,0 +1,10 @@ +--- +- name: Restart WireGuard + service: + name: "wg-quick@{{ wireguard_interface }}" + daemon_reload: True + enabled: True + state: restarted + listen: __wireguard_restart + become: True + become_user: root diff --git a/meta/main.yml b/meta/main.yml new file mode 100644 index 0000000..eb7a9b0 --- /dev/null +++ b/meta/main.yml @@ -0,0 +1,23 @@ +# Standards: 0.2 +--- +galaxy_info: + # @meta author:value: [Robert Kaussow](https://gitea.rknet.org/xoxys) + author: "Robert Kaussow " + namespace: xoxys + role_name: wireguard + # @meta description: > + # [![Source Code](https://img.shields.io/badge/gitea-source%20code-blue?logo=gitea&logoColor=white)](https://gitea.rknet.org/ansible/xoxys.wireguard) + # [![Build Status](https://img.shields.io/drone/build/ansible/xoxys.wireguard?logo=drone&server=https%3A%2F%2Fdrone.rknet.org)](https://drone.rknet.org/ansible/xoxys.wireguard) + # [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?label=license)](https://gitea.rknet.org/ansible/xoxys.wireguard/src/branch/main/LICENSE) + # + # Setup wireguard VPN. + # @end + description: Setup wireguard VPN + license: MIT + min_ansible_version: 2.10 + platforms: + - name: EL + versions: + - 7 + galaxy_tags: [] +dependencies: [] diff --git a/molecule/default b/molecule/default new file mode 120000 index 0000000..afa9fc6 --- /dev/null +++ b/molecule/default @@ -0,0 +1 @@ +rocky9 \ No newline at end of file diff --git a/molecule/pytest.ini b/molecule/pytest.ini new file mode 100644 index 0000000..c24fe5b --- /dev/null +++ b/molecule/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +filterwarnings = + ignore::DeprecationWarning diff --git a/molecule/requirements.yml b/molecule/requirements.yml new file mode 100644 index 0000000..46da115 --- /dev/null +++ b/molecule/requirements.yml @@ -0,0 +1,6 @@ +--- +collections: + - name: https://gitea.rknet.org/ansible/xoxys.general/releases/download/v2.1.1/xoxys-general-2.1.1.tar.gz + - name: community.general + +roles: [] diff --git a/molecule/rocky9/converge.yml b/molecule/rocky9/converge.yml new file mode 100644 index 0000000..5ed542f --- /dev/null +++ b/molecule/rocky9/converge.yml @@ -0,0 +1,5 @@ +--- +- name: Converge + hosts: all + roles: + - role: xoxys.wireguard diff --git a/molecule/rocky9/create.yml b/molecule/rocky9/create.yml new file mode 100644 index 0000000..719600d --- /dev/null +++ b/molecule/rocky9/create.yml @@ -0,0 +1,120 @@ +--- +- name: Create + hosts: localhost + connection: local + gather_facts: false + no_log: "{{ molecule_no_log }}" + vars: + ssh_port: 22 + ssh_user: root + ssh_path: "{{ lookup('env', 'MOLECULE_EPHEMERAL_DIRECTORY') }}/ssh_key" + tasks: + - name: Create SSH key + user: + name: "{{ lookup('env', 'USER') }}" + generate_ssh_key: true + ssh_key_file: "{{ ssh_path }}" + force: true + register: generated_ssh_key + + - name: Register the SSH key name + set_fact: + ssh_key_name: "molecule-generated-{{ 12345 | random | to_uuid }}" + + - name: Register SSH key for test instance(s) + hcloud_ssh_key: + name: "{{ ssh_key_name }}" + public_key: "{{ generated_ssh_key.ssh_public_key }}" + state: present + + - name: Create molecule instance(s) + hcloud_server: + name: "{{ item.name }}" + server_type: "{{ item.server_type }}" + ssh_keys: + - "{{ ssh_key_name }}" + image: "{{ item.image }}" + location: "{{ item.location | default(omit) }}" + datacenter: "{{ item.datacenter | default(omit) }}" + user_data: "{{ item.user_data | default(omit) }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: present + register: server + loop: "{{ molecule_yml.platforms }}" + async: 7200 + poll: 0 + + - name: Wait for instance(s) creation to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_jobs + until: hetzner_jobs.finished + retries: 300 + loop: "{{ server.results }}" + + - name: Create volume(s) + hcloud_volume: + name: "{{ item.name }}" + server: "{{ item.name }}" + location: "{{ item.location | default(omit) }}" + size: "{{ item.volume_size | default(10) }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: "present" + loop: "{{ molecule_yml.platforms }}" + when: item.volume | default(False) | bool + register: volumes + async: 7200 + poll: 0 + + - name: Wait for volume(s) creation to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_volumes + until: hetzner_volumes.finished + retries: 300 + when: volumes.changed + loop: "{{ volumes.results }}" + + # Mandatory configuration for Molecule to function. + + - name: Populate instance config dict + set_fact: + instance_conf_dict: + { + "instance": "{{ item.hcloud_server.name }}", + "ssh_key_name": "{{ ssh_key_name }}", + "address": "{{ item.hcloud_server.ipv4_address }}", + "user": "{{ ssh_user }}", + "port": "{{ ssh_port }}", + "identity_file": "{{ ssh_path }}", + "volume": "{{ item.item.item.volume | default(False) | bool }}", + } + loop: "{{ hetzner_jobs.results }}" + register: instance_config_dict + when: server.changed | bool + + - name: Convert instance config dict to a list + set_fact: + instance_conf: "{{ instance_config_dict.results | map(attribute='ansible_facts.instance_conf_dict') | list }}" + when: server.changed | bool + + - name: Dump instance config + copy: + content: | + # Molecule managed + + {{ instance_conf | to_nice_yaml(indent=2) }} + dest: "{{ molecule_instance_config }}" + when: server.changed | bool + + - name: Wait for SSH + wait_for: + port: "{{ ssh_port }}" + host: "{{ item.address }}" + search_regex: SSH + delay: 10 + loop: "{{ lookup('file', molecule_instance_config) | from_yaml }}" + + - name: Wait for VM to settle down + pause: + seconds: 30 \ No newline at end of file diff --git a/molecule/rocky9/destroy.yml b/molecule/rocky9/destroy.yml new file mode 100644 index 0000000..ed0b2ed --- /dev/null +++ b/molecule/rocky9/destroy.yml @@ -0,0 +1,78 @@ +--- +- name: Destroy + hosts: localhost + connection: local + gather_facts: false + no_log: "{{ molecule_no_log }}" + tasks: + - name: Check existing instance config file + stat: + path: "{{ molecule_instance_config }}" + register: cfg + + - name: Populate the instance config + set_fact: + instance_conf: "{{ (lookup('file', molecule_instance_config) | from_yaml) if cfg.stat.exists else [] }}" + + - name: Destroy molecule instance(s) + hcloud_server: + name: "{{ item.instance }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: absent + register: server + loop: "{{ instance_conf }}" + async: 7200 + poll: 0 + + - name: Wait for instance(s) deletion to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_jobs + until: hetzner_jobs.finished + retries: 300 + loop: "{{ server.results }}" + + - pause: + seconds: 5 + + - name: Destroy volume(s) + hcloud_volume: + name: "{{ item.instance }}" + server: "{{ item.instance }}" + api_token: "{{ lookup('env', 'HCLOUD_TOKEN') }}" + state: "absent" + register: volumes + loop: "{{ instance_conf }}" + when: item.volume | default(False) | bool + async: 7200 + poll: 0 + + - name: Wait for volume(s) deletion to complete + async_status: + jid: "{{ item.ansible_job_id }}" + register: hetzner_volumes + until: hetzner_volumes.finished + retries: 300 + when: volumes.changed + loop: "{{ volumes.results }}" + + - name: Remove registered SSH key + hcloud_ssh_key: + name: "{{ instance_conf[0].ssh_key_name }}" + state: absent + when: (instance_conf | default([])) | length > 0 + + # Mandatory configuration for Molecule to function. + + - name: Populate instance config + set_fact: + instance_conf: {} + + - name: Dump instance config + copy: + content: | + # Molecule managed + + {{ instance_conf | to_nice_yaml(indent=2) }} + dest: "{{ molecule_instance_config }}" + when: server.changed | bool \ No newline at end of file diff --git a/molecule/rocky9/molecule.yml b/molecule/rocky9/molecule.yml new file mode 100644 index 0000000..12f195e --- /dev/null +++ b/molecule/rocky9/molecule.yml @@ -0,0 +1,24 @@ +--- +dependency: + name: galaxy + options: + role-file: molecule/requirements.yml + requirements-file: molecule/requirements.yml + env: + ANSIBLE_GALAXY_DISPLAY_PROGRESS: "false" +driver: + name: delegated +platforms: + - name: rocky9-wireguard + image: rocky-9 + server_type: cx11 +lint: | + /usr/local/bin/flake8 +provisioner: + name: ansible + env: + ANSIBLE_FILTER_PLUGINS: ${ANSIBLE_FILTER_PLUGINS:-./plugins/filter} + ANSIBLE_LIBRARY: ${ANSIBLE_LIBRARY:-./library} + log: False +verifier: + name: testinfra diff --git a/molecule/rocky9/prepare.yml b/molecule/rocky9/prepare.yml new file mode 100644 index 0000000..183f4d3 --- /dev/null +++ b/molecule/rocky9/prepare.yml @@ -0,0 +1,15 @@ +--- +- name: Prepare + hosts: all + gather_facts: false + tasks: + - name: Bootstrap python for Ansible + raw: | + command -v python3 python || ( + (test -e /usr/bin/dnf && sudo dnf install -y python3) || + (test -e /usr/bin/apt && (apt -y update && apt install -y python-minimal)) || + (test -e /usr/bin/yum && sudo yum -y -qq install python3) || + echo "Warning: Python not boostrapped due to unknown platform." + ) + become: true + changed_when: false diff --git a/molecule/rocky9/tests/test_default.py b/molecule/rocky9/tests/test_default.py new file mode 100644 index 0000000..2dfb191 --- /dev/null +++ b/molecule/rocky9/tests/test_default.py @@ -0,0 +1,13 @@ +import os + +import testinfra.utils.ansible_runner + +testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( + os.environ["MOLECULE_INVENTORY_FILE"] +).get_hosts("all") + + +def test_wireguard_running_and_enabled(host): + wireguard = host.service("wg-quick@wg0") + assert wireguard.is_running + assert wireguard.is_enabled diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..2bb8674 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,12 @@ +[flake8] +ignore = D100, D101, D102, D103, D105, D107, E402, W503 +max-line-length = 99 +inline-quotes = double +exclude = .git,.tox,__pycache__,build,dist,tests,*.pyc,*.egg-info,.cache,.eggs,env* + +[yapf] +based_on_style = google +column_limit = 99 +dedent_closing_brackets = true +coalesce_brackets = true +split_before_logical_operator = true diff --git a/tasks/main.yml b/tasks/main.yml new file mode 100644 index 0000000..3935fb8 --- /dev/null +++ b/tasks/main.yml @@ -0,0 +1,79 @@ +--- +- name: Ensure dependencies are installed + package: + name: "{{ item }}" + state: present + loop: + - wireguard-tools + +- name: Stat WireGuard config file + stat: + path: "/etc/wireguard/{{ wireguard_interface }}.conf" + register: __wireguard_config_file + become: True + become_user: root + +- block: + - name: Generate WireGuard private key + command: "wg genkey" + register: __wireguard_private_key_gen + changed_when: false + + - name: Set private key fact + set_fact: + wireguard_private_key: "{{ __wireguard_private_key_gen.stdout }}" + when: + - not __wireguard_config_file.stat.exists + - wireguard_private_key is not defined + become: True + become_user: root + +- block: + - name: Read WireGuard config file + slurp: + src: "/etc/wireguard/{{ wireguard_interface }}.conf" + register: __wireguard_config + + - name: Set private key fact + set_fact: + wireguard_private_key: "{{ __wireguard_config['content'] | b64decode | regex_findall('PrivateKey = (.*)') | first }}" + when: + - __wireguard_config_file.stat.exists + - wireguard_private_key is not defined + become: True + become_user: root + +- block: + - name: Derive WireGuard public key + command: "wg pubkey" + args: + stdin: "{{ wireguard_private_key }}" + register: __wireguard_public_key_gen + changed_when: False + + - name: Set public key fact + set_fact: + __wireguard_public_key: "{{ __wireguard_public_key_gen.stdout }}" + + - name: Generate WireGuard configuration file + template: + src: etc/wireguard/wg.conf.j2 + dest: "/etc/wireguard/{{ wireguard_interface }}.conf" + owner: root + group: root + mode: 0600 + notify: __wireguard_restart + + - name: Ensure legacy reload-module-on-update is absent + file: + dest: "/etc/wireguard/.reload-module-on-update" + state: absent + + - name: Ensure WireGuard service is up and running + service: + name: "wg-quick@{{ wireguard_interface }}" + daemon_reload: True + enabled: True + state: started + become: True + become_user: root diff --git a/templates/etc/wireguard/wg.conf.j2 b/templates/etc/wireguard/wg.conf.j2 new file mode 100644 index 0000000..c1ec85d --- /dev/null +++ b/templates/etc/wireguard/wg.conf.j2 @@ -0,0 +1,80 @@ +#jinja2: lstrip_blocks: True +# {{ ansible_managed }} +[Interface] +## {{ inventory_hostname }} +Address = {{ wireguard_address }} +PrivateKey = {{ wireguard_private_key }} +ListenPort = {{ wireguard_port }} +{% if wireguard_dns is defined %} +DNS = {{ wireguard_dns }} +{% endif %} +{% if wireguard_fwmark is defined %} +FwMark = {{ wireguard_fwmark }} +{% endif %} +{% if wireguard_mtu is defined %} +MTU = {{ wireguard_mtu }} +{% endif %} +{% if wireguard_table is defined %} +Table = {{ wireguard_table }} +{% endif %} +{% if wireguard_preup is defined %} +{% for wg_preup in wireguard_preup %} +PreUp = {{ wg_preup }} +{% endfor %} +{% endif %} +{% if wireguard_postup is defined %} +{% for wg_postup in wireguard_postup %} +PostUp = {{ wg_postup }} +{% endfor %} +{% endif %} +{% if wireguard_predown is defined %} +{% for wg_predown in wireguard_predown %} +PreDown = {{ wg_predown }} +{% endfor %} +{% endif %} +{% if wireguard_postdown is defined %} +{% for wg_postdown in wireguard_postdown %} +PostDown = {{ wg_postdown }} +{% endfor %} +{% endif %} +SaveConfig = false +{% for host in wireguard_peers %} +{% if host != inventory_hostname %} + +[Peer] +## {{ host }} +PublicKey = {{ hostvars[host].__wireguard_public_key }} +{% if hostvars[host].wireguard_allowed_ips is defined %} +AllowedIPs = {{ hostvars[host].wireguard_allowed_ips }} +{% else %} +AllowedIPs = {{ hostvars[host].wireguard_address.split('/')[0] }}/32 +{% endif %} +{% if hostvars[host].wireguard_persistent_keepalive is defined %} +PersistentKeepalive = {{ hostvars[host].wireguard_persistent_keepalive }} +{% endif %} +{% if hostvars[host].wireguard_endpoint is not defined or hostvars[host].wireguard_endpoint != "" %} +Endpoint = {{ hostvars[host].wireguard_endpoint | default(host) }}:{{ hostvars[host].wireguard_port | default(wireguard_port) }} +{% endif %} +{% endif %} +{% endfor %} +{% if wireguard_peers_unmanaged | length > 0 %} + +# Peers not managed by Ansible +{% for peer in wireguard_peers_unmanaged %} +[Peer] +# {{ peer.name }} +PublicKey = {{ peer.public_key }} +{% if peer.preshared_key is defined %} +PresharedKey = {{ peer.preshared_key }} +{% endif %} +{% if peer.allowed_ips is defined %} +AllowedIPs = {{ peer.allowed_ips }} +{% endif %} +{% if peer.endpoint is defined %} +Endpoint = {{ peer.endpoint }} +{% endif %} +{% if peer.persistent_keepalive is defined %} +PersistentKeepalive = {{ peer.persistent_keepalive }} +{% endif %} +{% endfor %} +{% endif %}