DebugFactor.com | Forum

How to access a register variable in Ansible loop

I have a playbook similar to below.

- name: Test
  command: echo "{{item}}"
  loop: 
   - test1
   - test2
   - test3
  register: value

I am trying to print the output

- debug:
   msg: "{{value.rc}}"

But I don’t get the expected results, I get error - ‘dict object’ has no attribute ‘rc’

You cannot access an attribute of loop variable directly.
If you print the variable, you will see the output is in an array named results

  - name: print
    debug:
     msg: "{{value}}"

Output:

ok: [localhost] => {
    "msg": {
        "changed": true,
        "msg": "All items completed",
        "results": [
            {
                "ansible_loop_var": "item",
                "changed": true,
                "cmd": [
                    "echo",
                    "test1"
                ],
                "rc": 0",
                 .......

You have to provide the variable.results in loop and use item.rc instead. Please try as below.

  - debug:
     msg: "{{item.rc}}"
    loop: "{{value.results}}"