Run multiple lineinfile commands with with_items

0 votes

How can I achieve the following in ansible? I want to run multiple lineinfile within a list of servers.  I want to run several similar tasks on a list of servers. I didn't get any luck using with_nested

Jul 10, 2018 in Ansible by Nilesh
• 6,880 points
1,904 views

1 answer to this question.

0 votes

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

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' }

          ]

answered Jul 10, 2018 by Kalgi
• 2,620 points

Related Questions In Ansible

0 votes
1 answer

Is it possible to run commands on ansible host?

If you just trying to run a ...READ MORE

answered Jan 9 in Ansible by Vijay
142 views
0 votes
1 answer

Run Ansible adhoc commands in sequence

Hey @Thomas, by default ansible runs these ...READ MORE

answered Jan 14 in Ansible by Barbara
158 views
0 votes
1 answer

Is it possible to run a playbook with a crontab?

Ofcourse you can run ansible playbook with ...READ MORE

answered Jan 17 in Ansible by Yesha
548 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Requirements to run Ansible with Jenkins

These are the only requirements for running ...READ MORE

answered Apr 4 in Ansible by Himanshu
64 views
0 votes
1 answer
+13 votes
2 answers

Git management technique when there are multiple customers and need multiple customization?

Consider this - In 'extended' Git-Flow, (Git-Multi-Flow, ...READ MORE

answered Mar 26, 2018 in DevOps & Agile by DragonLord999
• 8,380 points
214 views