Home > Net >  Ansible - Overwrite values from file1 with coresponding value from file2
Ansible - Overwrite values from file1 with coresponding value from file2

Time:10-05

I have 2 files, file1 and file2.

I want ansible to read each line of file 2 and replace the values for the corresponding key in file1. These files could have more rows, I dont know how to exactly search and replace keys from file2 in file1 and replace corresponding values from file1 with values from file2. Any help is appreciated... :( Keys, will not be the same, so I can't hardcode I need to dynamically search and replace.

File 1 could have different format like .json .js .txt

ansible 2.7

key/value format might also be key=value

ex.
file1
 abc: cat
 def: horse
 test: house

file2
 def: airplane
 test: blue

Expected resulting file:
file1:
 abc: cat
 def: airplane
 test: blue

Thanks I will adapt to this module.

CodePudding user response:

I used the following tree for this example:

.
├── test.yml
└── vars
    └── merge_vars
        ├── file1.yml
        └── file2.yml

The var files are the same as in your question.

The example playbook:

---
- hosts: localhost
  gather_facts: false

  tasks:
    - name: import vars from files
      include_vars:
        dir: vars/merge_vars
        name: merged_vars

    - debug: 
        var: merged_vars

gives:

PLAY [localhost] ******************************************************************************************************************

TASK [import vars from files] *****************************************************************************************************
ok: [localhost]

TASK [debug] **********************************************************************************************************************
ok: [localhost] => {
    "merged_vars": {
        "abc": "cat",
        "def": "airplane",
        "test": "blue"
    }
}

PLAY RECAP ************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
  • Related