0

I want to create a file that shows the execution progress and what is being done when I run tasks. Now I want to generate a JSON format when I have done it through local_action and lineinfile.

This is my playbook

- name: The module that Set the progress and details
  block:
    - name: Set the progress and details
      shell: echo "10"
      register: progress_result
      delegate_to: localhost

    - name: Set the progress and details
      shell: echo "update docker script"
      register: message_result
      delegate_to: localhost

    - name: Save progress
      delegate_to: localhost
      local_action:
        module: lineinfile
        path: "{{playbook_dir}}/scheduler/plan.yaml"
        regexp: "progress:"
        line: "progress:{{progress_result.stdout}},step:{{message_result.stdout}}"
        create: yes

The current results of operation is

# cat scheduler/plan.yaml 
progress:10,step:update docker script

But I would like to have the results in JSON format

{"progress":"10","step":"update docker script"}

Who can help me?

U880D
  • 8,601
  • 6
  • 24
  • 40
zccharts
  • 41
  • 7

2 Answers2

1

That's nearly impossible with lineinfile, because your regexp and inserts must be valid json.

Instead of, you must re-read your file (lookup), parse from_json, append the json data and write it back to_json.

I'm interested why someone is tracking the ansible task process manually?

Markus
  • 2,998
  • 1
  • 21
  • 28
0

... some background information to the other given answer here.

To write out a line with double quotes within you could use an approach like

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    progress_result:
      stdout:  10

    message_result:
      stdout: update

  tasks:

  - name: Save progress
    lineinfile:
      path: test.txt
      regexp: "progress:"
      line: '"progress":"{{ progress_result.stdout }}","step":"{{ message_result.stdout }}"'
      create: yes

will result into an output of

"progress":"10","step":"update"

This will not apply for the curly braces ({,}).

Since your line to write does contain variables which need to be templated it will not be possible to use just !unsafe. Instead you could use {% raw %} and {% endraw %} to prevent templating on certain parts of the string.

      line: '{% raw %}{{% endraw %}"progress":"{{ progress_result.stdout }}","step":"{{ message_result.stdout }}{% raw %}"}{% endraw %}'

resulting into an output of

{'progress': '10', 'step': 'update'}

but which is then not valid JSON.

Similar Q&A


How to proceed further?

You may have a look into questions like

and as already mentioned in the other given answer here, as well

as they provide possible solutions.

U880D
  • 8,601
  • 6
  • 24
  • 40