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
• 7,060 points
6,981 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,680 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 10, 2019 in Ansible by Vijay
1,440 views
0 votes
1 answer

Run Ansible adhoc commands in sequence

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

answered Jan 14, 2019 in Ansible by Barbara
1,609 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, 2019 in Ansible by Yesha
4,909 views
0 votes
1 answer

Ansible Playbook for Creating a VM with OS and multiple data managed disks

Hey @Ammie, Try a playbook something like ...READ MORE

answered Mar 27, 2019 in Ansible by Stark
1,527 views
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, 2019 in Ansible by Himanshu
795 views
+1 vote
1 answer
+15 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 27, 2018 in DevOps & Agile by DragonLord999
• 8,450 points
4,062 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP