Bootstrap FreeKB - Ansible - Store output JSON in variable using the register parameter
Ansible - Store output JSON in variable using the register parameter

Updated:   |  Ansible articles

The register parameter can be used to store the JSON output of a task in a variable. In this example, the JSON output of the shell task will be stored in a variable named "out". Often, the debug module is then used to display the content of the variable.

---
- hosts: localhost
  tasks:
  - shell: ps
    register: out

  - debug:
      var: out
...

 

Which should output something like this.

TASK [shell] 
changed: [localhost]

TASK [debug] 
ok: [localhost] => {
    "out": {
        "changed": true, 
        "cmd": "ps", 
        "delta": "0:00:00.075407", 
        "end": "2022-09-29 03:06:03.478331", 
        "failed": false, 
        "rc": 0, 
        "start": "2022-09-29 03:06:03.402924", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "   PID TTY          TIME CMD\n 39957 pts/0    00:00:01 ansible-playboo\n 40165 pts/0    00:00:00 ansible-playboo\n 40238 pts/0    00:00:00 sh\n 40242 pts/0    00:00:00 python2\n 40253 pts/0    00:00:00 ps\n112376 pts/0    00:00:00 bash", 
        "stdout_lines": [
            "   PID TTY          TIME CMD", 
            " 39957 pts/0    00:00:01 ansible-playboo", 
            " 40165 pts/0    00:00:00 ansible-playboo", 
            " 40238 pts/0    00:00:00 sh", 
            " 40242 pts/0    00:00:00 python2", 
            " 40253 pts/0    00:00:00 ps", 
            "112376 pts/0    00:00:00 bash"
        ]
    }
}

 

You can also output just the value of a specific key, such as the stdout_lines key (in this example).

---
- hosts: localhost
  tasks:
  - shell: ps
    register: out

  - debug:
      var: out.stdout_lines
...

 

Which should output something like this.

ok: [localhost] => {
    "out.stdout_lines": [
        "   PID TTY          TIME CMD", 
        " 44334 pts/0    00:00:01 ansible-playboo", 
        " 44904 pts/0    00:00:00 ansible-playboo", 
        " 44926 pts/0    00:00:00 sh", 
        " 44929 pts/0    00:00:00 python2", 
        " 44946 pts/0    00:00:00 ps", 
        "112376 pts/0    00:00:00 bash"
    ]
}

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


January 12 2022 by Todd
How do you count how many times the word foo appears in the stdout?

January 12 2022 by Jeremy (moderator)
The length filter can be used to count the number of elements in an item. Here is my article on the length filter - http://www.freekb.net/Article?id=2969

January 22 2022 by Mijanur
Helpful one, thanks!

Add a Comment


Please enter 33817f in the box below so that we can be sure you are a human.