Ask Your Question
0

How can I use an ansible playbook to extract information from a txt file and transform it into JSON format?

asked 2022-05-21 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-23 16:00:00 +0000

huitzilopochtli gravatar image

You can use the following ansible playbook to extract information from a text file and transform it into JSON format:

---
- name: Extract information from text file and transform to JSON format
  hosts: localhost
  vars:
    text_file: "path/to/text_file.txt"
    json_file: "path/to/json_file.json"
  tasks:
    - name: Read text file
      slurp:
        src: "{{ text_file }}"
      register: text_file_data

    - name: Convert text file data to string
      set_fact:
        text_file_string: "{{ text_file_data['content'] | b64decode }}"

    - name: Transform text to JSON
      set_fact:
        json_data: "{{ text_file_string | regex_replace('(\\r\\n)|(\\n\\r)|\\r|\\n', '') | from_json }}"

    - name: Write JSON data to file
      copy:
        content: "{{ json_data | to_nice_json }}"
        dest: "{{ json_file }}"

In this playbook, we first use the slurp module to read the contents of the text file into a variable named text_file_data. We then use the b64decode filter to decode the contents of the file, since the slurp module returns base64-encoded data.

We use the set_fact module to store the decoded file contents as a string in a variable named text_file_string. We then use the regex_replace filter to remove any newline characters from the string, since they can cause issues when converting the string to JSON.

Finally, we use the from_json filter to convert the string to JSON format and store it in a variable named json_data. We use the to_nice_json filter to format the JSON data in a human-readable way, and then write it to a file using the copy module.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-21 11:00:00 +0000

Seen: 10 times

Last updated: Mar 23 '22