Search code examples
ansible

Replace a line in a config file with ansible


I am new to ansible.

Is there a simple way to replace the line starting with option domain-name-servers in /etc/dhcp/interface-br0.conf with more IPs?

  option domain-name-servers 10.116.184.1,10.116.144.1;

I want to add ,10.116.136.1


Solution

  • You can use the lineinfile Ansible module to achieve that.

      - name: replace line
        lineinfile: 
          path: /etc/dhcp/interface-br0.conf 
          regexp: '^(.*)option domain-name-servers(.*)$' 
          line: 'option domain-name-servers 10.116.184.1,10.116.144.1,10.116.136.1;'
          backrefs: yes
    

    The regexp option tells the module what will be the content to replace.

    The line option replaces the previously found content with the new content of your choice.

    The backrefs option guarantees that if the regexp does not match, the file will be left unchanged.