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,900 points

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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


    - lineinfile: dest=/tmp/testfile regexp={{item.regex}} line={{item.replace_with}}


        - 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


    - add_host: name={{ item }} groups=my_dynamic_group


        - server1

        - server2

- hosts: my_dynamic_group


    - lineinfile: dest=/tmp/testfile_{{ item[0] }} regexp={{item[1].regex}} line={{item[1].replace_with}} create=yes


        - [ '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
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
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
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
0 votes
1 answer
+13 votes
2 answers

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.