I know that you can copy a file from a remote server to the local using ansible with the fetch module.. You can even name the file with some variables related to the node you are fetching from. What I want to do, is to replace certain string on that file after copying it, ideally using inventory variables. Is this even possible? Is there any workaround that doesn't involves post-processing bash scripts?
After you have fetched the file, just use a delegation to localhost, via delegate_to, of a replace task.
Given /tmp/somefile
foo bar baz
This is an example string
Lorem Ipsum
The quick brown fox jumps over the lazy dog
And the playbook:
- hosts: all
  gather_facts: no
      
  tasks:
    - fetch:
        src: /tmp/somefile
        dest: /tmp/fetched
    - replace:
        path: /tmp/fetched/{{ inventory_hostname }}/tmp/somefile
        regexp: "^This is an example string$"
        replace: "{{ inventory_hostname }}"
      delegate_to: localhost
It yields the recap:
PLAY [all] *********************************************************************************************************
TASK [fetch] *******************************************************************************************************
changed: [host1]
TASK [replace] *****************************************************************************************************
changed: [host1 -> localhost]
PLAY RECAP *********************************************************************************************************
host1                      : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
And gives the file /tmp/fetched/host1/tmp/somefile containing:
foo bar baz
host1
Lorem Ipsum
The quick brown fox jumps over the lazy dog
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With