Stepan Kuksenko
Stepan Kuksenko

Reputation: 345

How to replace all strings after a certain line in ansible?

I need to remove all strings in file hosts and add one line after string "127.0.0.1 localhost".

I have tried to use module replace with after, but I don't understand what I need to put in "after":

- name: Add new hostname after 127.0.0.1 localhost and remove old lines
  replace:
    path: /etc/hosts
    regexp: '^(\S+)(\s+)localhost\.domain\.com(\s+.*)?$'
    replace: '{{ new_hostname }}'
    after: '' 

Upvotes: 0

Views: 501

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

You'll be better off with template

For example template hosts.j2

127.0.0.1                localhost
{% for item in my_hosts %}
{{ item }}
{% endfor %}

with playbook

- hosts: localhost
  vars:
    my_hosts:
      - 10.1.0.1 ac1.example.com ac1
      - 10.1.0.2 ac2.example.com ac2
      - 10.1.0.3 ac3.example.com ac3
  tasks:
    - template:
        src: hosts.j2
        dest: /etc/hosts

gives

> cat /etc/hosts
127.0.0.1                localhost
10.1.0.1 ac1.example.com ac1
10.1.0.2 ac2.example.com ac2
10.1.0.3 ac3.example.com ac3

Upvotes: 1

Related Questions