Kelvin A. Vasquez
Kelvin A. Vasquez

Reputation: 65

Regular expression not finding any matches to replace text using ansible.builtin.replace

I have this Ansible task from a playbook that I am trying to use to replace the occurrences of a hostname found in /etc/hosts with a new hostname set as a variable in /etc/ansible/hosts:

  - name: Update /etc/hosts
    replace:
      path: /etc/hosts
      regexp: '^\w+-\w+'
      replace: "{{ new_hostname }}"

The hostname of the Ansible target that I am trying to change the contents of /etc/hosts is webna-host0011, which is also the pattern I am trying to capture in /etc/hosts and replace all occurrences of.

When I run the playbook, this task is not finding any matches to do a replace on and the /etc/hosts file remains unchanged.

I checked the regular expression using https://pythex.org/ with webna-host0011 as my test string and was able to get the right match, but this expression finds no matches when used in the task itself.

This is /etc/hosts itself:

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

10.12.52.19     webna-host0011.onegrp.com webna-host0011

The regular expression matches the hostname itself, but it seems like the match cannot be made due to where it is in the lines of the file itself.

Upvotes: 2

Views: 736

Answers (1)

Frenchy
Frenchy

Reputation: 17017

in your case ie, without rules to define the hostname to replace :

 - name: Update /etc/hosts
    replace:
      path: /etc/hosts
      regexp: 'webna-host0011'
      replace: "{{ new_hostname }}"

or to replace all strings which contains a - in it (be careful):

 - name: Update /etc/hosts
    replace:
      path: /etc/hosts
      regexp: \w+-\w+'
      replace: "{{ new_hostname }}"

Upvotes: 2

Related Questions