Regex and Grouping in Ansible

One of the challenges when working with Ansible is manipulating strings effectively. While Ansible provides various modules, such as file and lineinfile, to process the content of files, certain tasks can still be tricky. Recently, I encountered a task where I needed to capture the hostname and replace it in a YAML file. To maintain the spacing structure inherent to YAML, I had to rely on regex and capture the required information using a group.

Example:

- name: Example
  ansible.builtin.lineinfile:
    path: /tmp/config
    regexp: (\s+)hostname:\s
    line: \1hostname{{":"}} {{ ansible_hostname }}
    backrefs: yes

This article was updated on January 19, 2025