Miguel Ping
Miguel Ping

Reputation: 18347

Run multiple lineinfile commands with with_items

How can I achieve the following in ansible? I want to run multiple lineinfile within a list of servers.

If I do the following, ansible complains because of the repeated lineinfile

- name: ensure /etc/environment is correct
  tags: env
  with_items: "{{ hosts }}"
  lineinfile: dest=/etc/environment regexp=^PROFILE=line=PROFILE={{prof}}
  lineinfile: dest=/etc/environment regexp=^OTHER=line=OTHER={{other}}

I tried to nest with_items to no avail.

Upvotes: 0

Views: 6936

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68319

Here is the example playbook to ensure file /tmp/testfile has PROFILE set to my_new_profile and OTHER set to my_new_other on both server1 and server2:

- hosts: server1, server2
  tasks:
    - lineinfile: dest=/tmp/testfile regexp={{item.regex}} line={{item.replace_with}}
      with_items:
        - regex: ^PROFILE=
          replace_with: PROFILE=my_new_profile
        - regex: ^OTHER=
          replace_with: OTHER=my_new_other

Update: using dynamic group and nested loop to create two files: testfile_host1 and testfile_host2 with lines present on all servers in my_dynamic_group group created earlier in playbook.

- hosts: localhost
  tasks:
    - add_host: name={{ item }} groups=my_dynamic_group
      with_items:
        - server1
        - server2

- hosts: my_dynamic_group
  tasks:
    - lineinfile: dest=/tmp/testfile_{{ item[0] }} regexp={{item[1].regex}} line={{item[1].replace_with}} create=yes
      with_nested:
        - [ 'host1', 'host2' ]
        - [
            { regex: '^PROFILE=', replace_with: 'PROFILE=my_new_profile' },
            { regex: '^OTHER=',   replace_with: 'OTHER=my_new_other' }
          ]

Upvotes: 3

Related Questions