Premchand
Premchand

Reputation: 51

Ansible - replace particular string in multiple files if file exists

I can replace a string in the file if the file exists in a directory.

Similarly, I want to replace the string in another 25 files (test2.conf .. test25.conf) if the files exist in the same directory. Using with_items I can able to replace a string in all files but unable to use the register to check the file exists in the loop.

Below playbook is a success for one file, how can I achieve the same for 25 files?

     - hosts: webserver  

       vars:
    strings:
       - user1
       - user2

  tasks:  
     - name: Check /home/user/test1.conf exists
       stat:  
          path: /home/user/test1.conf  
       register: stat_result


 - name:  Replace string in test1.conf
   replace:
     dest: /home/user/test1.conf
     backup: yes
     regexp: '^Hello'
     replace: "Hello {{ strings | join(' ')}}"
   when: stat_result.stat.exists == True 

Upvotes: 1

Views: 4780

Answers (1)

techraf
techraf

Reputation: 68559

Use find module instead of stat and iterate over the results:

- hosts: webserver  

  vars:
    strings:
      - user1
      - user2

  tasks:  
    - name: Get a list of test*.conf in /home/user
      find:  
        paths: /home/user
        patterns: test*.conf
       register: my_find

    - name: Replace strings in files found
      replace:
        dest: "{{ item.path }}"
        backup: yes
        regexp: '^Hello'
        replace: "Hello {{ strings | join(' ')}}"
      with_items: "{{ my_find.files }}"

Your replace task is not idempotent, it will add strings infinitely on subsequent runs.

Upvotes: 2

Related Questions