Pages

Wednesday, 27 November 2019

EX294: Use variables to retrieve the results of running a command

official doc link: register variables

0. Basic Idea

Ansible modules return JSON data. To make use of this returned data, Ansible can save a module's return as a variable, which is done by directive "register". From then on, the following tasks can reference this variable.

---
- hosts: home
  gather_facts: no
  tasks:
      - name: get data time
        shell: date '+%Y%m%d %H:%M:%S'
        register: result

      - name: print result
        debug: var=result
Let's have a look at what's the return data of the above example.

$ ansible-playbook playbook.yml
PLAY [home] ************************************************************************************************

TASK [get date time] **********************************************************************************
changed: [192.168.0.19]

TASK [print result] ****************************************************************************************
ok: [192.168.0.19] => {
    "result": {
        "ansible_facts": {
            "discovered_interpreter_python": "/usr/bin/python"
        },
        "changed": true,
        "cmd": "date '+%Y%m%d %H:%M:%S'",
        "delta": "0:00:00.009413",
        "end": "2019-11-27 22:55:25.818248",
        "failed": false,
        "rc": 0,
        "start": "2019-11-27 22:55:25.808835",
        "stderr": "",
        "stderr_lines": [],
        "stdout": "20191127 22:55:25",
        "stdout_lines": [
            "20191127 22:55:25"
        ]
    }
}

1 Key points

  • registered variables are at the host-level, just like facts.
  • registered variables are saved in memory
  • registered variables can only be used by tasks running on the same host
  • different modules return different data, please see their doc for data format

No comments:

Post a Comment