Working with Ansible Register Variables

Ansible registers are used when you want to capture the output of a task to a variable. You can then use the value of these registers for different scenarios like a conditional statement, logging etc.

The variables will contain the value returned by the task. The common return values are documented in Ansible docs. Some of the modules like shell, command etc. have module specific return values. These will be documented in the module docs.

Each registered variables will be valid on the remote host where the task was run for the rest of the playbook execution.

Basic Example of a Register Variables

Let us see how we can capture the output of a task to a register. Suppose you need to print all the .txt files in a particular folder. You can execute the ls *.txt command using a shell module and capture the output to a variable.

Suppose you need to print all the .txt files in a particular folder. You can execute the ls *.txt command using a shell module and capture the output to a variable.

In the following example, I have captured the output to ‘find_output’ variable. Yo can see all the returned values in the output section.

- hosts: all
  tasks:
  - name: Ansible register variable basic example
    shell: "find *.txt"
    args:
      chdir: "/Users/mdtutorials2/Documents/Ansible"
    register: find_output

  - debug:
      var: find_output

output
======

ok: [localhost] => {
    "find_output": {
        "changed": true, 
        "cmd": "find *.txt", 
        "delta": "0:00:00.008597", 
        "end": "2017-09-30 15:07:15.940235", 
        "rc": 0, 
        "start": "2017-09-30 15:07:15.931638", 
        "stderr": "", 
        "stderr_lines": [], 
        "stdout": "check.txt\ncheck2.txt", 
        "stdout_lines": [
            "check.txt", 
            "check2.txt"
        ]
    }
}

You can select the individual parameter from the above output by appending the name with the return value. For example, if you need only the file names then you can use find_output.stdout.

  - debug:
      var: find_output.stdout

output
======
"find_output.stdout": "check.txt\ncheck2.txt"

Iterating through ansible register using with_items

You can loop through the register variables using the with_items statement. It is very useful when you need to use the individual values. In the following task, I am trying to make a backup of all the text files. For that, first I will store the variables in a register and iterate through each file. The stdout_lines will return the stdout split line by line.

- hosts: all
  tasks:
  - name: Ansible register with_items example
    shell: "find *.txt"
    args:
      chdir: "/Users/mdtutorials2/Documents/Ansible"
    register: with_output

  - shell: "cp {{ item }} {{item}}_bkp"
    with_items:
      - "{{ with_output.stdout_lines }}"

After the execution check.txt_bkp and check2.txt_bkp are created.

For more information on how to work with loops in Ansible, you can refer this post.