Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy a file from remote server and replace a string using ansible

Tags:

ansible

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?

like image 606
Danielo515 Avatar asked Oct 16 '22 01:10

Danielo515


1 Answers

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
like image 191
β.εηοιτ.βε Avatar answered Oct 21 '22 03:10

β.εηοιτ.βε