Replacing variable in multiple file

16 views
Skip to first unread message

Abdulrazzaq shaik

unread,
Sep 7, 2020, 12:03:24 AM9/7/20
to Ansible Project
vars:
    - MACHINE: gpack.tmt.com
    - AMSPORT: 9933
    - ENVIRONMENT: 'PRD'
    - PROJECT: 'GTA'
    - AMSPORT: '333'
    - MACHINE_LOG: ' gpack  '
    - STOREFILE_PATH: '/home/linux/store'
    - AMS_VERSION: '1.5'

I have few file in the node need to change all above variable in the different place in the file.

Kindly share how i can do it in one shot

    - name: Replace string in files 
      replace:
        dest: "{{ item.path }}"
        regexp: 'AMSPORT'
        replace: '{{AMSPORT}}'
      loop_control:
        label: "{{ item.path }}"
      with_items: "{{ files_to_change.files }}"

by above i can able to change only one variable at a time,

Please help in sharing how this can be done in all files replacing all variables.

Vladimir Botka

unread,
Sep 7, 2020, 1:51:24 AM9/7/20
to Abdulrazzaq shaik, ansible...@googlegroups.com
On Sun, 6 Sep 2020 21:03:24 -0700 (PDT)
Abdulrazzaq shaik <shaikabdu...@gmail.com> wrote:

> vars:
> - MACHINE: gpack.tmt.com
> - AMSPORT: 9933
> ...
> - name: Replace string in files
> replace:
> dest: "{{ item.path }}"
> regexp: 'AMSPORT'
> replace: '{{AMSPORT}}'
> loop_control:
> label: "{{ item.path }}"
> with_items: "{{ files_to_change.files }}"
>
> ... all files replacing all variables.

In this case, the best option is the "nested" loop
https://docs.ansible.com/ansible/latest/plugins/lookup/nested.html#nested-composes-a-list-with-nested-elements-of-other-lists

Two lists are needed. A list of the files and a list of the
variables. Instead of the list of hashes it would be easier to use a
dictionary

my_vars:
MACHINE: gpack.tmt.com
AMSPORT: 9933

The output of the task below shows how to create the loop
and the parameters

- debug:
msg:
- "dest: {{ item.0.path }}"
- "regexp: {{ item.1 }}"
- "replace: {{ my_vars[item.1] }}"
with_nested:
- "{{ files_to_change.files }}"
- "{{ my_vars.keys()|list }}"

If this is what you want replace the variables in the files

- name: Replace string in files
replace:
dest: "{{ item.0.path }}"
regexp: "{{ item.1 }}"
replace: "{{ my_vars[item.1] }}"
with_nested:
- "{{ files_to_change.files }}"
- "{{ my_vars.keys()|list }}"

--
Vladimir Botka
Reply all
Reply to author
Forward
0 new messages