GithubHelp home page GithubHelp logo

githubixx / ansible-role-wireguard Goto Github PK

View Code? Open in Web Editor NEW
563.0 12.0 177.0 223 KB

Ansible role for installing WireGuard VPN. Supports Ubuntu, Debian, Archlinx, Fedora and CentOS.

Home Page: https://www.tauceti.blog/post/kubernetes-the-not-so-hard-way-with-ansible-wireguard/

Jinja 100.00%
wireguard vpn linux security networking ansible ansible-role

ansible-role-wireguard's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ansible-role-wireguard's Issues

Variables to set server public/private key

Maybe it cannot be considered as a best practice, but when having a lots of clients already configured, it is very impractical to bother everyone to change their configuration when we re-deploy our WireGuard instance.

ansible-vault is used, and the private key is occasionally rotated. Doing this tasks can be recommended in the documentation.

Execute lifecycle hooks upon reconfiguration to maintain consistency

Managing iptables rules is a common example for using wg-quick's lifecycle hooks PreUp, PostUp, PreDown and PostDown. However, when changing those rules and deploying this role again they're not executed since just the plain wg configuration is sync'ed. What's worse, after updating the configuration WireGuard can't be even restarted with wg-quick since deleting a non-existing iptables rule results in an error which in turn aborts the shutdown halfway through.

Suppose the following PostUp and PreDown rules are deployed:

wireguard_postup:
  - iptables -A FORWARD -i %i -j ACCEPT
  - iptables -A FORWARD -o %i -j ACCEPT
  - iptables -t nat -A POSTROUTING -i %i -o eth0 -j MASQUERADE
# Generate inverse iptables commands
wireguard_predown: "{{ wireguard_postup | reverse | replace('-A', '-D') }}"

When I add a new rule (e. g. iptables -A INPUT -i % -j REJECT) to wireguard_postup and deploy the role again the configuration file contains two new lines: one PostUp and one PreDown entry (containing the new rule and its counterpart). When I try to restart WireGuard the counterpart of the new rule is already executed leading to an error.

On the otherhand, when I remove an iptables rule from wireguard_postup its counterpart is removed as well and won't be executed when restarting WireGuard leaving the system in an unclean state.

One way of resolving this issue is to shutdown the interface before updating the configuration file and starting it up again after the update. This comes with several challenges, though:

  • Active connections will be interrupted (which might not be that big of a problem in a private network environment)
  • To achieve idempotence we don't want to shutdown WireGuard if the configuration didn't change
  • In order to run the *Down rules of the old (currently active) configuration we cannot update the configuration before shutting down the interface

Since there might be even more side effects I don't anticipate I'd like to start a discussion on that topic. Thank you in advance.

Make directory/file mode bits configurable

Currently the directory specified in wireguard_cert_directory has fixed permissions set to 0700. A wireguard_cert_directory_permission variable should be introduced with a default setting of 0700 to make it configurable but keeping the current setting as default.

Also the file permissions of the certificate files should be configurable while using the current settings as defaults to not change the current behaviour.

"Add WireGuard repository" fails on Ubuntu 18.04

TASK [githubixx.ansible_role_wireguard : (Ubuntu) Add WireGuard repository (for Ubuntu < 19.10)] *******************************************************************************

fatal: [bastion]: FAILED! =>  {
    "changed": false,
    "invocation": {
        "module_args": {
            "codename": null,
            "filename": null,
            "install_python_apt": true,
            "mode": null,
            "repo": "ppa:wireguard/wireguard",
            "state": "present",
            "update_cache": true,
            "validate_certs": true
        }
    },
    "msg": "failed to fetch PPA information, error was: HTTP Error 404: Not Found"
}

It seems ppa:wireguard/wireguard no longer exists.

I tried the command manually:

$ add-apt-repository ppa:wireguard/wireguard
Cannot add PPA: 'ppa:~wireguard/ubuntu/wireguard'.
The team named '~wireguard' has no PPA named 'ubuntu/wireguard'
Please choose from the following available PPAs:

This is on

$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 18.04.1 LTS
Release:	18.04
Codename:	bionic

setting wg0.conf in only 1 host from group

Hi again , i need set the configuration in only 1 host from a group

i have

[aws_fws]
fw1.aws.local
fw2.aws.local

the variables are in the file

inventory/host_var/fw1/wireguard.yml

if I do

ansible-playbook wireguard.yml --limit="fw1.aws.local" 

everything is OK in 1 host... BUT

if i do in my playbook the same thing

- name: Configure Wireguard
  hosts: aws_fws
  gather_facts: yes

  vars:

  vars_files:

  roles:
    - role: wireguard
      when: inventory_hostname == 'fw1.aws.local'

i receive this error...

The full traceback is:
Traceback (most recent call last):
  File "/usr/local/bin/python_virtualenvs/ansible-4.3.0-devops_env9/lib/python3.8/site-packages/ansible/template/__init__.py", line 1100, in do_template
    res = j2_concat(rf)
  File "<template>", line 119, in root
  File "/usr/local/bin/python_virtualenvs/ansible-4.3.0-devops_env9/lib/python3.8/site-packages/jinja2/runtime.py", line 903, in _fail_with_undefined_error
    raise self._undefined_exception(self._undefined_message)
jinja2.exceptions.UndefinedError: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'wireguard__fact_public_key'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/bin/python_virtualenvs/ansible-4.3.0-devops_env9/lib/python3.8/site-packages/ansible/plugins/action/template.py", line 146, in run
    resultant = templar.do_template(template_data, preserve_trailing_newlines=True, escape_backslashes=False)
  File "/usr/local/bin/python_virtualenvs/ansible-4.3.0-devops_env9/lib/python3.8/site-packages/ansible/template/__init__.py", line 1137, in do_template
    raise AnsibleUndefinedVariable(e)
ansible.errors.AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'wireguard__fact_public_key'
fatal: [fw1.aws.local]: FAILED! => changed=false
  msg: 'AnsibleUndefinedVariable: ''ansible.vars.hostvars.HostVarsVars object'' has no attribute ''wireguard__fact_public_key'''

fw1.yml

---
wireguard_interface: wg0
wireguard_address: 192.168.20.1/32
wireguard_endpoint: "{{ ansible_hostname }}.aws.local"
wireguard_dns: "aws.local"
wireguard_port: 51820

wireguard_unmanaged_peers:
  laptop:
    public_key: .......public_key......
    allowed_ips: 192.168.20.2/32"

wireguard_postup:
  - iptables -t nat -A POSTROUTING -o {{ ansible_default_ipv4.interface }} -j MASQUERADE
  - iptables -A FORWARD -i {{ wireguard_interface }} -j ACCEPT
  - iptables -A FORWARD -o {{ wireguard_interface }} -j ACCEPT
  - iptables -A INPUT -i {{ wireguard_interface }} -j ACCEPT
  - iptables -A OUTPUT -o {{ wireguard_interface }} -j ACCEPT

wireguard_postdown:
  - iptables -t nat -D POSTROUTING -o {{ ansible_default_ipv4.interface }} -j MASQUERADE
  - iptables -D FORWARD -i {{ wireguard_interface }} -j ACCEPT
  - iptables -D FORWARD -o {{ wireguard_interface }} -j ACCEPT
  - iptables -D INPUT -i {{ wireguard_interface }} -j ACCEPT
  - iptables -D OUTPUT -o {{ wireguard_interface }} -j ACCEPT

More robust error handling

I like this role and use it to manage 20+ nodes mesh.
The main issue I have is that if one node fails for whatever reason, it's excluded from the configuration and when the rest of the nodes are updated, they don't contain the key & IP of the failed node. This causes the node to be excluded and lose connectivity.

Most of the times I've hit this problem, a node had some silly minor issue I wasn't aware of (last example, expired cert for extra apt source) and unless I'm watching the script run, ready to cancel it, it ruins well-running node.

I'd like to see option where the play run is cancelled on the first error from a node.

cannot redefine wireguard_port:

Hi,

I would like to connect few servers behind NAT to my mesh
They all have the same wireguard_endpoint:
But different: wireguard_port:

subsequently, ports are forwarded outside

but in every generated wg0.conf
all the peers in Endpoint have always the same port like the ListenPort
The endpoint address is a correct one

Switch to ELRepo for RHEL/Centos

I'm using this role to install wireguard on Centos7/8 systems. In recent update to Centos 7.8 wireguard caused problems(kernel panic at boot). It updated kernel, however wireguard kernel module wasn't updated.

I troubleshooted issue and found that this role installed dkms-wireguard package from jdoss repository, which seems to be not maintained properly. I found that official wireguard webpage recommends to use ELRepo and kmod-wireguard package https://www.wireguard.com/install/. I manually switched to this repository and it worked perfectly. Extra bonus for getting rid of dependencies for building dkms.

We should also add some task to properly uninstall old repository and dkms package.

I would make PR if you would like.

Tag wg-install is not applied properly

Hi altogether,

first of all: Thank you for this role - helped me rolling out wireguard on my hosts.

As I do have some hosts, that do run custom distros, the install tasks do not cover those.
No problem here - I think I've build myself some edge cases there.

But because of this, I've tried using the existing tag "wg-install" to skip any installation tasks and found it not working.
After a short inspection of the tasks, I've found a solution, that I'll provide in a PR later today.

This issue is more for documentation purposes than asking for a fix. :)

Support use of wireguard-go on non-OS X platforms

Not all Linux hosts have access to their kernel (e.g. LXD containers, OpenVZ guests) to load a kernel module. For such environments, wireguard-go is required: it would be great if this role could provide such support.

Configure additional peers

In my use case some peers share a network (I'll call it "local network") and another peer is outside of that network. The outside peer is accessible from the peers in the local network, but not the other way around. This ansible role already works for that use case, but I'd like to configure additional peers so that the traffic inside the local network isn't sent to the outside peer but directly inside the local network to the other peers.

Adding Peers while wg interface is UP

Adding a peer to the ansible config results in the existing wg interface to be destroyed and restarted.
Instead it would be nice if just the peer was added to the already-existing configuration.

Generate configuration for non-Ansible peers

Similar to #63, cc @joneskoo but the other way around.

What do you think about an option where the role could generate ready to use WireGuard configuration files that are not Ansible managed (for example phones). The convenient way to do this is to generate the private key, template the configuration and then provide it to the end device.

For implementation, I am thinking about adding those hosts actually to the Ansible inventory but with connection local. Then run the role against them and have the config redirected into a "secret" directory on the Ansible controller. I have done something like this with https://github.com/ypid/ansible-packages already. Works.

See also #65 (comment) and #66 for my background.

Debian role fails (ansible_lsb)

Role fails to execute on my Debian hosts due to ansible_lsb being empty.

Is there a better way to detect Raspbian or maybe have a check to see if ansible_lsb is populated?
The host in question is running Buster and all LSB named packages are installed, lsb-base & lsb-release.

[ansible]$ ansible node1 -m setup -a 'filter=ansible_lsb'
node1 | SUCCESS => {
    "ansible_facts": {
        "ansible_lsb": {},
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false
}

Need for storing state locally?

Hi,

thanks for writing and sharing this role, this is really nice!

I have a question, is it necessary to store the state locally?
It would be easy to check if the server is already configured, find the private key and derive the public key, and if not, create the private key?

Am I missing something?

If you agree that storing the state is not so necessary, I can PR, to remove this need.

Cheers!

certs own by root

Hi

I am running the role from ubuntu 16.04 to a bunch of ubuntu 16.04 machines
The role fails on TASK [ansible-role-wireguard : Read private key]
with messages like
"Unable to find '/home/kisiel/wireguard/certs/hcloud1.vpn.private.key' in expected paths (use -vvvvv to see paths)"

"kisiel" is the user running ansible
the problem is that the /home/kisiel/wireguard/ was created with ownership to root
is this an error?

hide peers without endpoint to enable routing via other wireguard host

Hi!

In my current setup I use wireguard to manage very different hosts. Some are globally reachable servers, but most devices are behind firewalls. I need the possibility to access all devices from my own 'management' laptop, which is itself a device without global endpoint. Therefore, I have one dedicated wireguard server that serves as router between all NAT-ted devices. This 'router' has my whole IP range assigned as AllowedIPs. However, the routing does not work if the NAT-ted devices are set as peers without endpoints, because then routing requests (using ping) fail with ping: sendmsg: Destination address required.

Furthermore, devices without an endpoint also don't need to have a ListenPort as this port will never be used.

I suggest:

  • to hide ListenPort, if the Endpoint is empty
  • to hide the whole Peer section for devices whose Endpoint is empty

Best regards,
Miroka

Wireguard dkms on Ubuntu 16.04

On ubuntu 16.04 the task (Ubuntu) Ensure WireGuard DKMS package is removed removes wireguard and wireguard-dkms.
But the task (Ubuntu) Install wireguard package than reinstalls wireguard and wireguard-dkms.

ansible.vars.hostvars.HostVarsVars object has no attribute wireguard__fact_public_key

I could read this error has been mentioned in previous issues but none of their resolutions seems to help in my case. I hope someone here might have a bright idea.

I previously ran this role months ago successfully. Today I've formatted one of the servers in the network. Since I install it with Ansible I'veupdated the role before running le playbook. Unfortunately I face this error.

TASK [wireguard : Generate WireGuard configuration file] **********************************************************************************************************************************************************************************************************************************************************
fatal: [svr1.local.domain.net]: FAILED! => changed=false
  msg: 'AnsibleUndefinedVariable: ''ansible.vars.hostvars.HostVarsVars object'' has no attribute ''wireguard__fact_public_key'''
fatal: [svr2.local.domain.net]: FAILED! => changed=false
  msg: 'AnsibleUndefinedVariable: ''ansible.vars.hostvars.HostVarsVars object'' has no attribute ''wireguard__fact_public_key'''

My host file looks like the following:

    vpn:
      children:
        vpn_xymon:
          hosts:
            svr1.local.domain.net:
              wireguard_address: "10.8.0.9/24"
            svr2.local.domain.net:
              wireguard_address: "10.8.0.6/24"

What's wrong? :(

simple configuration

Hi again @githubixx

2 questions

how could be the simple configuration in my host_var for server/client to works this role ?

if i have

1- host_var/aws_wg_server # wireguard server

2- host_var/on_premise_server # client server to connect to wireguard server


i put on server side vars
wireguard_address: "1.2.3.4/24"
wireguard_endpoint: aws.wg.server

and i see the configuration on server with private key but missing public from peer.. .so.?

Split the main task

I'm tempted to split the main task into various smaller chunks that would be more readable, would it be ok for you?

manage firewall if present and active

Hi, first of all, thank you very much for your work on this. Many people profited.

I'd be surprised if this never came up before but one issue that I ran into while deploying this some of my servers out there was that one of them had a firewall running, ufw to be precise. Do you agree it might make sense to open the respective wireguard_port on all hosts by default?

Support for mutliple wireguard vpn on same host.

Ok, now I know it is a bit more I'm asking, but I really don't want to fork your project, and I'd prefer to collaborate here :)

Basically, We run on hetzner too, and we have a kubernetes cluster on baremetal instance, and we have ceph, and 10g net cards.
So I'd like one wireguard for kube, one for ceph frontend, and one for ceph backend.

I see how I can do it with your role, but it will not be backward compatible.

Basically:

#instance-1 host_var
wireguard:
 - wg0:
    - address: 10.0.0.1/24
       port: 51820
 - ceph-backend:
    - address: 10.0.1.1/24
       port: 51821
#instance-2 host_var
wireguard:
 - wg0:
    - address: 10.0.0.2/24
       port: 51820
 - ceph-backend:
    - address: 10.0.1.2/24
       port: 51821

And then I'd loop over these keys and derive the interface name from there.

What do you think? Can I PR? (I'll do it anyway for me ;) )

No support for roaming peers

There is no support for roaming peers because every node expects every-other peer to have a resolvable endpoint. Roaming peers (like a laptop) will never have resolvable endpoints so there must be a way to omit them from being present in other peer configs.

The issue comes from the config file template around this part.

{% for host in ansible_play_hosts %}
  {% if host != inventory_hostname %}
  
    [Peer]

Suggest adding a new variable wireguard_roaming to omit peers that are roaming.

{% for host in ansible_play_hosts %}
  {% if host != inventory_hostname %}
  
    [Peer]
    ...
    {% if hostvars[host].wireguard_roaming is undefined or not hostvars[host].wireguard_roaming %}
    ...
    {% endif %}
  {% endif %}
{% endfor %}

Generate static conf [no connect hosts]

Can you tell me if it is possible to generate keys and put them in a file without connecting via ssh? I have routers that require a specific setup.

Original[ru]
Подскажите можно ли сгенерировать ключи и положить их в файл не подключаясь по ssh. У меня есть роутеры которым требуется специфичная установка.

CentOS 7 hardening and ELRepo

Running the role on a hardened CentOS 7 instance requires installing the elrepo GPGkey in order to install the module. More importantly, the module is not signed. While it installs, this error is observed in dmesg "Request for unknown module key 'The ELRepo Project (http://elrepo.org/): ELRepo.org Secure Boot Key: f365ad3481a7b20e3427b61b2a26635b83fe427b' err -11
wireguard: module verification failed: signature and/or required key missing - tainting kernel". This can be remedied by installing the key (http://elrepo.org/tiki/SecureBootKey), but this requires UEFI key management.

Per https://www.wireguard.com/install/, there are 3 methods to install WireGuard on CentOS 7:
Method 1: a signed module is available as built-in to CentOS's kernel-plus:
$ sudo yum install yum-utils epel-release
$ sudo yum-config-manager --setopt=centosplus.includepkgs=kernel-plus --enablerepo=centosplus --save
$ sudo sed -e 's/^DEFAULTKERNEL=kernel$/DEFAULTKERNEL=kernel-plus/' -i /etc/sysconfig/kernel
$ sudo yum install kernel-plus wireguard-tools
$ sudo reboot

Method 2: users wishing to stick with the standard kernel may use ELRepo's pre-built module:
$ sudo yum install epel-release elrepo-release
$ sudo yum install yum-plugin-elrepo
$ sudo yum install kmod-wireguard wireguard-tools

Method 3: users running non-standard kernels may wish to use the DKMS package instead:
$ sudo yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
$ sudo curl -o /etc/yum.repos.d/jdoss-wireguard-epel-7.repo https://copr.fedorainfracloud.org/coprs/jdoss/wireguard/repo/epel-7/jdoss-wireguard-epel-7.repo
$ sudo yum install wireguard-dkms wireguard-tools

The role currently uses the second option, which uses the standard kernel and requires no reboots. I have forked the role here: https://github.com/john-p-potter/ansible-role-wireguard/tree/kernel-plus and submitted MR #129 to upstream to address this issue.

NAT / keepalive logic

At the moment, according to the example in the readme, the wireguard endpoint behind a NAT should have keepalive configured. This configures keepalives from all hosts to the host behind NAT. But shouldn't it be the other way around? The NATed endpoint needs to send keepalives to the other endpoints to be reachable.
The problem is, if the NATed endpoint doesn't send any frame over wireguard, the tunnel never comes up because the other endpoints can't send keepalives to the endpoint behind the nat. That's problematic if an endpoint, or a network, behind the nat should be accessible.

I think either the logic needs to be the other way around or maybe a ping from the device behind the nat to the other endpoints added to the role could help to initialize the tunnel.

Or do I miss something?

Ubuntu (and systemd) DNS specifics

Executive summary: when the DNS option is set, wg-quick does not run on Ubuntu without openresolv. Installing (and using) openresolv, messes up with the standard way resolution is handled (via systemd-resolved). Use systemd-resolve on such distros to properly inject WG DNS servers.

I'm working around this by keeping the DNS empty and using the following command in PostUp:
systemd-resolve -i wg0 --set-dns=10.99.1.10 --set-dns=10.99.1.11 --set-dns=10.99.1.12

Would be nice if the role detected this and implemented the workaround automatically.

Alternative is to use systemd's netdevs, but that's pretty heavy-handed change.

Ubuntu 2004 missing resolvconf package by default.

Hello

The role doesn't check if resolvconf is installed on ubuntu-2004. Installing the package resolves the error.

root@vpn:/etc/wireguard# journalctl -u wg-quick@wg0
-- Logs begin at Fri 2021-07-30 14:30:50 UTC, end at Fri 2021-07-30 15:50:08 UTC. --
Jul 30 15:38:41 vpn systemd[1]: Starting WireGuard via wg-quick(8) for wg0...
Jul 30 15:38:41 vpn wg-quick[24657]: [#] ip link add wg0 type wireguard
Jul 30 15:38:41 vpn wg-quick[24657]: [#] wg setconf wg0 /dev/fd/63
Jul 30 15:38:42 vpn wg-quick[24657]: [#] ip -4 address add 192.168.1.52/32 dev wg0
Jul 30 15:38:42 vpn wg-quick[24657]: [#] ip link set mtu 1420 up dev wg0
Jul 30 15:38:42 vpn wg-quick[24681]: [#] resolvconf -a wg0 -m 0 -x
Jul 30 15:38:42 vpn wg-quick[24683]: /usr/bin/wg-quick: line 32: resolvconf: command not found
Jul 30 15:38:42 vpn wg-quick[24657]: [#] ip link delete dev wg0
Jul 30 15:38:42 vpn systemd[1]: [email protected]: Main process exited, code=exited, status=127/n/a
Jul 30 15:38:42 vpn systemd[1]: [email protected]: Failed with result 'exit-code'.
Jul 30 15:38:42 vpn systemd[1]: Failed to start WireGuard via wg-quick(8) for wg0.
root@vpn:/etc/wireguard# cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.2 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.2 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal

AnsibleUndefinedVariable: HostVarsVars object has no attribute 'public_key'

Quite new to Ansible, trying to get wireguard setup between a number of machines but am getting an error as below (let me know if you need the entire log). Is there a step I'm missing here, there doesn't seem to be anything in the readme about setting public keys, and if I understand it correctly, set public key fact should set this attribute.

TASK [wireguard : Set public key fact] ***************************************************************************************************
ok: [1.1.1.1]
ok: [2.2.2.2]
ok: [3.3.3.3]

TASK [wireguard : Create WireGuard configuration directory] ******************************************************************************
ok: [1.1.1.1]
ok: [2.2.2.2]
ok: [3.3.3.3]

TASK [wireguard : Generate WireGuard configuration file] *********************************************************************************
fatal: [1.1.1.1]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'public_key'"}
fatal: [2.2.2.2]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'public_key'"}
fatal: [3.3.3.3]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'public_key'"}

setup-debian.yml not able to setup debian but ubuntu instead ..

Debian script should be like this depend on WireGuard doc


- name: Setup WireGuard preference
  command: "printf 'Package: *\nPin: release a=unstable\nPin-Priority: 90\n' > /etc/apt/preferences.d/limit-unstable"
  tags:
    - wg-install

- name: Add WireGuard key
  apt_key:
    keyserver: "keyserver.ubuntu.com"
    id: "8B48AD6246925553"
    state: present
  run_once: true
  tags:
    - wg-install

- name: Add WireGuard repository
  apt_repository:
    repo: "deb http://deb.debian.org/debian/ unstable main"
    state: present
    update_cache: yes
  run_once: true
  tags:
    - wg-install

Feature request: add detection for Proxmox kernel

Description

It appears the DKMS kernel header detection doesn't account for Proxmox kernel, which although is a parasite of Debian, but have kernel of its own (specifically speaking, Proxmox uses free Debian repos but uses a Ubuntu kernel fork with inclusions of ZFS and Ceph -- weird mix but ok)

Synopsis

You should see a fatal message in playbook task procedures:

TASK [githubixx.ansible_role_wireguard : (Debian) Install kernel headers for the currently running kernel to compile Wireguard with DKMS] ***********************************************************************
fatal: [storage]: FAILED! => {"changed": false, "msg": "No package matching '**linux-headers-5.4.78-2-pve**' is available"}

Indeed, apt install linux-headers-5.4.78-2-pve doesn't show any positive result, and in fact it should be pve-headers.

Solution

Add the proxmox kernel identifier pve-headers to the conditions to check kernel header installation

Workaround

Skip that specific task when the distribution is Proxmox based, and ensure you manually installed the kernel headers.

Background

I wished to create my Proxmox cluster in a WireGuard based network fabric over the internet, because it seems you need a LAN IP to make corosync happy.

No package matching 'linux-headers-4.19.0' is available

Got this error on my debian servers:

TASK [githubixx.ansible_role_wireguard : (Debian) Install kernel headers for the currently running kernel to compile Wireguard with DKMS] ***
fatal: [host1]: FAILED! => {"changed": false, "msg": "No package matching 'linux-headers-4.19.0' is available"}
fatal: [host2]: FAILED! => {"changed": false, "msg": "No package matching 'linux-headers-4.19.0' is available"}

Using ansible-role-wireguard version '8.4.0' from ansible galaxy.
Debian 10.11 with kernel 4.19.0.

I first thought it is similar to #62, but this fix should be already in, right?

Combined effort with DebOps?

Hey there, DebOps developer here. I found your role to be the best starting point to add WireGuard support to DebOps and would like to have your feedback on it.

For now, I see these viable options:

  1. Make the role itself auto detect (Ansible local facts) when it runs against a DebOps managed host and behave in a compatibly way. Additionally, as DebOps is a comprehensive approach to configuration management, I would need to maintain a wrapper role in DebOps that manages the Firewall. An example how this can look like is DebOps’s tor relay role: https://github.com/debops/debops/tree/master/ansible/roles/tor and its corresponding playbook:
    https://github.com/debops/debops/blob/master/ansible/debops-contrib-playbooks/service/tor.yml This is an intermidiate option but it would avoid the forking that I don’t like.

  2. Fork the role and make it a native DebOps role following https://docs.debops.org/en/master/dep/dep-0002.html

    Edit: That is kinda unavoidable. I started this work at https://github.com/ypid/ansible-wireguard/tree/prepare-for-debops

  3. We update the role and move it to DebOps :)

This is not urgent for me. I will open a improvement PR and a second one to add DebOps compatibility following option 1 and then you can have a look at the code.

Also note that DebOps has a role which solves similar problems of setting up a distributed public key system, https://docs.debops.org/en/master/ansible/roles/tinc/index.html. I will look into this older role again to compare your design with this one. Note that the tinc role has not be reworked since 2017 so it is not the most up-to-date one. There are more high-quality once if you want to check one out.

See also b-m-f/WirtBot#61 for my strategy.

Stable config when running against a subset of the initial ansible_play_hosts

The current design is modeled around ansible_play_hosts:

{% for host in ansible_play_hosts %}

This has one very strong downside which is that this role cannot run against one host because then it would remove all of the peers from that one host. I am currently looking into using inventory groups for this like in https://docs.debops.org/en/master/ansible/roles/tinc/index.html as part of #66. I opened this issue here because I think it is relevant for others as well. Note that there are more changes needed to solve this issue than just inventory groups.

A common thing to do is to have a "site" playbook which runs all roles against a server and which can fully deploy it. This is kinda incompatible with this role currently.

Fixed in: https://github.com/ypid/ansible-wireguard/tree/prepare-for-debops

`wireguard_cert_owner` demands local root access - is that necessary?

Hi,

Using your role as a non root leads to

TASK [githubixx.ansible_role_wireguard : Create WireGuard certificates directory] ***********************************************************************************************
fatal: [master-0.k8s.gr8pi.org -> localhost]: FAILED! => {"changed": false, "gid": 1000, "group": "ieugen", "mode": "0755", "msg": "chown failed: [Errno 1] Operation not permitted: b'/home/user/production/ansible/wireguard-certs'", "owner": "user", "path": "/home/user/production/ansible/wireguard-certs", "size": 4096, "state": "directory", "uid": 1000}

Is the permission change necessary to be done locally ? If not I think it might make the role much portable.

wireguard_cert_owner: "root"
wireguard_cert_group: "root"

Linux header installation fails on Raspberry pi

Installation fails on Raspberry Pi with Raspbian : setup-debian.yml tries to install "linux-headers-{{ dpkg_arch.stdout }}", however, in Raspbian the package is called linux-headers (without arch).

Install requires specific version

Hi,

Ansible galaxy complains, fails to find version.

You need to specify the exact version ansible-galaxy install githubixx.ansible_role_wireguard,3.2.0

 gr8pi-production git:(gr8pi-prod) ✗ ansible-galaxy install githubixx.ansible_role_wireguard      
- downloading role 'ansible_role_wireguard', owned by githubixx
 [WARNING]: - githubixx.ansible_role_wireguard was NOT installed successfully: Unable to compare role versions (2.0.1, 3.0.0, 3.0.1, 3.1.0, 3.2.0,
v1.0.2, v1.0.1, 2.0.0, v1.0.0) to determine the most recent version due to incompatible version formats. Please contact the role author to resolve
versioning conflicts, or specify an explicit role version to install.

no attribute 'public_key'

Hi,

I am losing my mind, what I might be doing wrong to get this on each host?

FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.vars.hostvars.HostVarsVars object' has no attribute 'public_key'"}

Flush handlers at the end of the role

This ensures the syncconf is called at the end of the role before moving on, otherwise it's only called at the end of the play.

The code would look like:

- name: Force all notified handlers to run
  meta: flush_handlers

Debian vanilla tasks fetches headers ahead of current kernel

The host I'm trying to target currently runs kernel 4.19.0-9-amd64, which is one patch (is this the correct name?) version behind the current release (4.19.0-10). As it's not a -cloud- tagged kernel, the debian-vanilla tasks attempt to fetch linux-headers-amd64, which pulls headers from a version outside my current kernel.

This makes wireguard's modprobe step fail, as it can't find the module for 4.19.0-9. Upgrading the kernel is not an option at the moment

I can provide execution logs if necessary, just let me know.

Steps to reproduce

I managed to make this reproducible via Vagrant:

Vagrant.configure("2") do |config|
  config.vm.box = "debian/buster64"

  config.vm.define "vpn"

  config.vm.provision "ansible" do |ans|
    ans.playbook = "../config-management/site.yaml" # Or any yaml that just includes the wireguard role
    ans.groups = {
      "vpn" => ["vpn"],
    }
    ans.host_vars = {
      "vpn" => {
        "wireguard_address" => "10.0.0.2/24"
      }
    }
  end
end

Workaround diff

I managed to make the role work on my use case by applying the following diff. However, I do not know the consequences this change could have on other environments:

diff --git a/tasks/setup-debian-vanilla.yml b/tasks/setup-debian-vanilla.yml
index 0b6aa0b..b45ce72 100644
--- a/tasks/setup-debian-vanilla.yml
+++ b/tasks/setup-debian-vanilla.yml
@@ -19,7 +19,7 @@
   changed_when: False

 - set_fact:
-    kernel_header_version: "{{ ('-cloud-' in ansible_kernel) | ternary(ansible_kernel,dpkg_arch.stdout) }}"
+    kernel_header_version: "{{ ansible_kernel }}"

 - name: (Debian) Install kernel headers to compile Wireguard with DKMS
   apt:

CentOS 8

Hi... i'm trying to implement this role by default on CentOS 8 ...

kernel: 4.18
centos version: 8.3.2011

output

fatal: [firewall]: FAILED! => changed=false
  attempts: 10
  failed_when_result: true
  invocation:
    module_args:
      name: wireguard
      params: ''
      state: present
  msg: |-
    modprobe: FATAL: Module wireguard not found in directory /lib/modules/4.18.0-240.1.1.el8_3.x86_64
  name: wireguard
  params: ''
  rc: 1
  state: present
  stderr: |-
    modprobe: FATAL: Module wireguard not found in directory /lib/modules/4.18.0-240.1.1.el8_3.x86_64
  stderr_lines: <omitted>
  stdout: ''
  stdout_lines: <omitted>

Put private key into separate file instead of main config

Reasons:

  • Avoid shoulder surfing and the like. You know the case when you show someone your config and it contains secrets? This not just looks unprofessional, it is also avoidable :)
  • Simplify the parsing of the configuration. Currently some regex parsing is done. That is not even needed.
  • Allow show/log diffs without revealing secrets (etckeeper, Ansible).
  • Will go in line with my Ansible controller based key management approach discussed in #65.
  • The native wg set subcommand only accepts files. When we already have files, we can manipulate wg interfaces easier.
  • Supported natively by systemd netdev. Ref: https://www.freedesktop.org/software/systemd/man/systemd.netdev.html#PrivateKeyFile=

Example:

PostUp = wg set %i private-key /etc/wireguard/%i.privkey

Downsides:

  • Will require automated migration. Doable.

What do you think?

The same should then be done for PSKs, although I have no file naming schema yet.

SaveConfig is always true

Even when setting wireguard_save_config: "false" explicitly on each host or for the group, all of their configurations will have SaveConfig = true present.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.