1
votes

I've tried a lot many ways to get this done in Ansible, I still get stuck :/

So, I have to read credentials (user & password) from one file:

file1: (dest: /home/usr/Desktop/file1.txt)

#this is a cred file
number= 8910334
user= xyz  #(this maybe username=xyz also)
password= abc

After reading the file content, I need to split where ever I find a ('=') sign with 'user' & 'password' based on the following:

user key= user

user value= xyz

password key= password

password value= abc

file2: (dest: /home/usr/Desktop/file2.txt)

#Hi, I need credentials
school= spsg
user =         #(this value may be blank or may be filled with some other entry or it may be xyz.user.name=   )
password=    #(this value may be blank or may be filled with some other entry or it may be xyz.password.value= )

Now, in file2, I want the user=________ value & password=________ value replaced by the extracted user value & password value from file1. (the line number of user & password may vary, so don't fix the line numbers as [1] & [2] respectively)

Also, along with file2, there are some more files which need the values from file1, so it would be better if this task is done with loops.

Please suggest me with possible YAML code for getting this done. Thanks :)

1

1 Answers

1
votes

If the file is not local fetch it. Then the task below

  vars:
    file_name: file1.txt
  tasks:
    - set_fact:
        my_vars: "{{ my_vars|default([]) +
                     [{'key': item, 'value': my_value}] }}"
      loop: "{{ lookup('pipe', my_cat).splitlines()|
                select('match', my_regex_comment)|
                map('regex_replace', my_regex, my_replace)|
                map('trim')|
                list }}"
      vars:
        my_regex_comment: '^(?!\s*\#).*$'  # filter commented line
        my_regex_any_comment: '(\s*\#.*)'  # match comment in value
        my_regex: '^(.*?)=(.*)$'           # match key and value
        my_replace: '\1'                   # replace with key
        my_replace_empty: ""               # delete
        my_cat: "{{ 'cat ' ~ file_name }}"
        my_ini: "{{ item ~ ' type=properties file=' ~ file_name }}"
        my_value: "{{ lookup('ini', my_ini)|
                      regex_replace(my_regex_any_comment, my_replace_empty) }}"
    - debug:
        var: my_vars

gives

  my_vars:
  - key: number
    value: '8910334'
  - key: user
    value: xyz
  - key: password
    value: abc

Use template to write the file. For example the task and the template below

    - template:
        src: file2.txt.j2
        dest: file2.txt
shell> cat file2.txt.j2
{% for item in my_vars %}
{{ item.key }}={{ item.value }}
{% endfor %}

give

shell> cat file2.txt
number=8910334
user=xyz
password=abc

The next option is to use lineinfile to add, or replace the variables in the loop

    - lineinfile:
        path: file2.txt
        regex: '^\s*{{ item.key }}\s*=(.*)$'
        line: '{{ item.key }}={{ item.value }}'
      loop: "{{ my_vars }}"