regexgrepwireguard

Regex get IP from Wireguard conf file


To automate the deployment of our Wireguard VPN connection I need a Regex expression to get the assigned IP for a user in the configuration file for Wireguard.

The file looks like this, with a Block for each user:

[Interface]
PrivateKey = ***********
Address = 10.0.0.1
ListenPort= ***
# BEGIN ANSIBLE MANAGED BLOCK name1.lastname1
[Peer]
PublicKey = ******
AllowedIPs = 10.0.0.2
# END ANSIBLE MANAGED BLOCK name1.lastname1
# BEGIN ANSIBLE MANAGED BLOCK name2.lastname2
[Peer]
PublicKey = ******
AllowedIPs = 10.0.0.3
# END ANSIBLE MANAGED BLOCK name2.lastname2

I just want the AllowedIP returned for a spacific user.

By now I have something like this: name1.lastname1(?s)(?:.*?)AllowedIPs = (?s)(.*?)# END

This somehow works on this site: regex101.com But if i try to grep it in the command line I don't get anything returned.

Can anyone help me with this?

Thank you in advance.


Solution

  • grep -A4 "^# BEGIN.*name1.lastname1" CONFIGFILE | grep "^AllowedIPs" | cut -d " " -f3
    

    This solution will show only the first IP and assumes the user config block contains the IP within the first 4 lines. (you should adjust the A4 after checking the variance).

    1. By the fist grep the relevant part of the user block is is isolated, containing only one line with an IP declaration.
    2. By the second grep the result is limited to the line with the IP
    3. The cut eliminates everything except the first IP in the line.

    Using awk would give better control for more reliable results.