0

My Problem is that I want to replace a random (most of the time) APIPA address, which gets assigned to a interface when you install a new Debian machine, with, for example, the IP address 1.1.1.1. I want to replace it with the Ansible "regex and replace" method.

I use Ansible 2.9

Here is something I tried but it doesn't work:

- name: Replace multiple lines and entries
    replace:
      path: /etc/network/interfaces.d/vm
      regexp: "{{ '({0-9}{1,3}{\\.}){3}{0-9}{1,3}' }}"
      replace: "5.5.5.5"

And here's how the vm file looks like:

# qemu (virtio_net driver)
allow-hotplug enp0s2
iface enp0s2 inet dhcp

# vbox (virtio_net driver)
allow-hotplug enp0s3
iface enp0s3 inet dhcp

# vmware (vmxnet3 driver)
allow-hotplug ens192
iface ens192 inet dhcp
  address 12.80.55.47/27


allow-hotplug ens224
iface ens224 inet static
 address 192.168.1.77/28
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • Might be an unrelated remark, but why would you template something that is a literal string? Do `regexp: '({0-9}{1,3}{\\.}){3}{0-9}{1,3}'` instead – β.εηοιτ.βε Aug 25 '22 at 13:56
  • 1
    A range in a regexp is surrounded by square brackets, not curly braces. Moreover, @β.εηοιτ.βε remark above is entirely right. Next, backslashes inside single quotes in yaml have nothing special and should not be escaped (see https://learnxinyminutes.com/docs/yaml/). And lastly, I did not reallly get what you are trying with curly braces around matching a period but that is wrong. => `regexp: '([0-9]{1,3}\.){3}[0-9]{1,3}'` Please check your syntax prior to asking a question. A good online resource for regexps is https://regex101.com/ – Zeitounator Aug 25 '22 at 14:22
  • I personally prefer the following notation which will give the same result regarding the global match and respects the DRY principle: `([0-9]{1,3})(\.(?1)){3}` – Zeitounator Aug 25 '22 at 14:35
  • Note that this is still very simplified and will not validate IPs out of the 0.0.0.0-255.255.255.255 range. If you need something that is more robust, see https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp – Zeitounator Aug 25 '22 at 14:47
  • Thanks guys, I took everything in consideration and fixed it – noobienoob7 Aug 29 '22 at 07:55

0 Answers0