Regarding the comments "You need to register the output of the command in order for Ansible to store it." and "I tried register before, but I cannot find a way to use the register variable in the shell of other play." you may have look into the following minimal example playbook

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

  tasks:

  - name: 4. Verify key generation
    shell:
      cmd: "gpg --list-secret-keys --keyid-format=long | sed '4!d' | tr -d ' '"
    register: VAR

  - name: 6. Echo GPG ID
    shell:
      cmd: "echo {{ VAR.stdout_lines }}"
    register: result

  - name: Show result
    debug:
      var: result

or a more generic

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

  tasks:

  - name: Echo example 1
    shell:
      cmd: "echo 12:34:56:78:90:AB:CD:EF"
    register: VAR

  - name: Echo example 2
    shell:
      cmd: "echo {{ VAR.stdout_lines }}"
    register: result

  - name: Show registered variable
    debug:
      var: result

  - name: Show result content only
    debug:
      msg: "{{ result }}"

as it shows you how to get familiar with registering, return values and data structures.

Further Documenation

  • Registering variables
  • Common Return Values
  • shell Return Values
  • debug module – Print statements during execution
Answer from U880D on Stack Exchange
🌐
EDUCBA
educba.com › home › software development › software development tutorials › ansible tutorial › ansible register
Ansible Register | Guide to How Ansible Register Work with Examples
May 17, 2023 - - hosts: all tasks: name: find all txt files in /tmp shell: "find /tmp -name *.txt" register: find_output debug: var: find_output · After executing it, we will see the below output; in this output, under stdout_lines, we will know the name of files that are found. Output: ansible-playbook register_variable_task_find.yaml ·
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Ansible
forum.ansible.com › archives › ansible project
Ansible register stdout_lines - Ansible Project - Ansible
December 19, 2022 - Hi team Need your support I’m looking out for put loop on register stdout _lines my stdout_lines output is this “stdout_lines”: [ “NAME READY STATUS RESTARTS AGE”, “kafka-0 1/1 Running 3 (3h1m ago) 3d”, “kafka-1 1/1 Running 3 (3h1m ago) 3d”, “kafka-zookeeper-0 1/1 Running 1 (3h2m ago) 3d” ] My playbook task is this name: List of {{release_name}} pods shell: kubectl get pods -l ‘app.kubernetes.io/component in (zookeeper,kafka)’ register: pod_output when: pod_status is succeeded debu...
Discussions

Ansible: Use stdout_lines from registered variable which uses loop in shell module - Stack Overflow
Wondering if anyone here can help... I'm running Ansible 2.10.7 - The below Ansible task is responsible for checking whether or not any JBOSS deployments exist from a previous Ansible run or not. If More on stackoverflow.com
🌐 stackoverflow.com
register, with_items and stdout_lines
I think the problem is the conditional when is keeping the task from executing (at least on one host in the inventory group) which means the variable is never defined by the register since the task is skipped. Then you get an undefined error. More on reddit.com
🌐 r/ansible
8
4
September 2, 2018
ansible - Take shell cmd stdout_lines and create dict from output - DevOps Stack Exchange
I am using needrestart -b to get the following example output NEEDRESTART-VER: 3.6 NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64 NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64 NEEDRESTART-... More on devops.stackexchange.com
🌐 devops.stackexchange.com
How to grab last two lines from ansible (register stdout) initialization of kubernetes cluster - Stack Overflow
This is the piece of my playbook file for the question: - name: Initialize the Kubernetes cluster using kubeadm command: kubeadm init --config /etc/kubernetes/kubeadminit.yaml register: More on stackoverflow.com
🌐 stackoverflow.com
🌐
OneUptime
oneuptime.com › home › blog › how to capture command output with register in ansible
How to Capture Command Output with register in Ansible
February 21, 2026 - # what_register_captures.yml - Inspect the registered variable structure --- - name: Explore registered variable contents hosts: localhost connection: local tasks: - name: Run a simple command ansible.builtin.command: cmd: echo "hello world" register: result - name: Display the full registered variable ansible.builtin.debug: var: result - name: Display individual fields ansible.builtin.debug: msg: | stdout: {{ result.stdout }} stdout_lines: {{ result.stdout_lines }} stderr: {{ result.stderr }} stderr_lines: {{ result.stderr_lines }} rc (return code): {{ result.rc }} changed: {{ result.changed }} cmd: {{ result.cmd }} start: {{ result.start }} end: {{ result.end }} delta: {{ result.delta }}
🌐
Ansible
docs.ansible.com › projects › ansible › latest › reference_appendices › common_return_values.html
Return Values — Ansible Community Documentation
When stdout is returned, Ansible always provides a list of strings, each containing one item per line from the original output. ... These keys can be added by modules but will be removed from registered variables; they are ‘consumed’ by Ansible itself.
🌐
OSTechNix
ostechnix.com › home › it automation › ansible › ansible register variable
Ansible Register Variable - OSTechNix
September 22, 2022 - Stdout, Stdout_lines - Stdout messages. Take a look at the below task. Instead of printing the entire output of the register variable, I am just trying to print the return code. - name: Just checking the exit code ansible.builtin.debug: msg: "{{ virtualenv_output.rc }}"
🌐
Linux Hint
linuxhint.com › ansible_register_module
How to Use Ansible Register Module – Linux Hint
Same as stderr, but stderr separates the lines using newlines (\n) characters instead of arrays. If you just want to print/access the password string (which is very likely), you may print/access the stdout property of the mypass variable in your playbook, as marked in the screenshot below.
Find elsewhere
🌐
Google Groups
groups.google.com › g › ansible-project › c › QUugEQRZT-g
using register stdout_lines in with_items loop
- name: get list of directories shell: "egrep '^archive.directory|^outgoing.directory|^incoming.directory' {{conf_dir}}/{{item.1.config}}|cut -d '=' -f2|sort|uniq" with_subelements: - "{{loggers}}" - configs register: directoriesToBuild - name: debug directory output debug: msg: "{{directoriesToBuild.results|map(attribute='stdout_lines')|list}}" - name: build found directories file: state: directory path: "{{item}}" with_items: - "{{directoriesToBuild.results|map(attribute='stdout_lines')|list}}" ... To unsubscribe from this group and stop receiving emails from it, send an email to ansible...@googlegroups.com.
🌐
Reddit
reddit.com › r/ansible › register, with_items and stdout_lines
r/ansible on Reddit: register, with_items and stdout_lines
September 2, 2018 -

It's my understanding that using register with a loop and trying to output the information in stdout format, Ansible stores the results in a more complex way and it's not that easy to access the .stdout.

Here is what I'm trying to work with:

- name: "vs_profile_type"   
  prompt: "enter the profile to run your pre-checks against [Enter in the following format: tcp tcp, http http]"   
  private: no 

 tasks:
      - name : Checking which LTM is active....
        bigip_command:
          server: "{{ inventory_hostname }}"
          user: "{{ remote_username }}"
          password: "{{ remote_passwd }}"
          commands:
            - "tmsh show sys failover"
          validate_certs: no
        delegate_to: localhost
        register: Active_LTM

      - name: The active LTMs management IP is....
        block:
          - debug:
              var: Active_LTM.stdout[0]

      - name: Profile_Pre-check
        bigip_command:
          server: "{{ inventory_hostname }}"
          user: "{{ remote_username }}"
          password: "{{ remote_passwd }}"
          commands:
             - "tmsh list ltm profile {{ item }}"
          validate_certs: no
        delegate_to: localhost
        with_items:
          - "{{ vs_profile_type.split(',') }}"
        when: "'active' in Active_LTM['stdout'][0]"
        register: Active_LTM_Pre_Checks

      - name: Please verify the profile pre-checks are correct
        debug:
          var: Active_LTM_Pre_Checks.stdout_lines

The problem comes when the play gets to the debug section and it throws an error saying that the variable "Active_LTM_Pre_Checks.stdout_lines" is not defined. I've done some searching but haven't been able to find a solution yet on how to accomplish this

🌐
Super User
superuser.com › questions › 1830848 › how-to-print-stdout-of-results-variable-of-previous-task
ansible - How to print stdout of results variable of previous task - Super User
February 19, 2024 - - name: Enabling the repoistory shell: subscription-manager repos --enable={{ item }} register: _repostatus loop: "{{ repo_id }}" - debug: msg: "{{ item.stdout }}" loop: "{{ _repostatus.stdout_lines }}" And it print all the variables which i dont need to see · _repostatus: changed: true msg: All items completed results: - ansible_loop_var: item changed: true cmd: subscription-manager repos --enable=rhel-7-server-extras-rpms delta: '0:00:04.035395' end: '2024-02-19 10:43:14.323637' failed: false invocation: module_args: _raw_params: subscription-manager repos --enable=rhel-7-server-extras-rpms
🌐
Mydailytutorials
mydailytutorials.com › ansible-register-variables
Mydailytutorials
September 30, 2017 - We cannot provide a description for this page right now
Top answer
1 of 1
2

A: The value of command_results.stdout_lines is the YAML list. Nothing happens to the list when you filter it from_yaml. Use command_results.stdout instead

- set_fact:
    needrestart: "{{ command_results.stdout | from_yaml }}"

Details: Given the below file for testing

shell> cat needrestart.txt 
NEEDRESTART-VER: 3.6
NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
NEEDRESTART-KSTA: 2
NEEDRESTART-UCSTA: 0

Please read it

    - command: cat needrestart.txt
      register: command_results

You can see that next to the YAML list in the attribute stdout_lines

  command_results.stdout_lines:
  - 'NEEDRESTART-VER: 3.6'
  - 'NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64'
  - 'NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64'
  - 'NEEDRESTART-KSTA: 2'
  - 'NEEDRESTART-UCSTA: 0'

there is also the YAML text bloc in the attribute stdout

  command_results.stdout: |-
    NEEDRESTART-VER: 3.6
    NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KSTA: 2
    NEEDRESTART-UCSTA: 0

Now, you can use from_yaml to (quote):

Converts a YAML string representation into an equivalent structured Ansible variable.

For example,

  needrestart: "{{ command_results.stdout | from_yaml }}"

gives what you want

  needrestart:
    NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KSTA: 2
    NEEDRESTART-UCSTA: 0
    NEEDRESTART-VER: 3.6

  needrestart['NEEDRESTART-VER']: '3.6'

Notes:

  • If you have a list only there are more options. You can convert the items to YAML dictionaries and combine them
  n3: "{{ command_results.stdout_lines | map('from_yaml') | combine }}"

gives the same result

  n3:
    NEEDRESTART-KCUR: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KEXP: 5.14.0-362.24.1.el9_3.0.1.x86_64
    NEEDRESTART-KSTA: 2
    NEEDRESTART-UCSTA: 0
    NEEDRESTART-VER: 3.6

  n3['NEEDRESTART-VER']: '3.6'
  • The next option is using the function dict on the split items. The below declaration also gives the same result
    n4: "{{ dict(command_results.stdout_lines | map('split', ':')) }}"
  • Example of a complete playbook for testing
- hosts: localhost

  vars:

    n1: "{{ command_results.stdout_lines | from_yaml }}"
    n2: "{{ command_results.stdout | from_yaml }}"
    n3: "{{ command_results.stdout_lines | map('from_yaml') | combine }}"
    n4: "{{ dict(command_results.stdout_lines | map('split', ':')) }}"

  tasks:

    - command: cat needrestart.txt
      register: command_results

    - debug:
        var: command_results.stdout_lines
    - debug:
        var: command_results.stdout

    - debug:
        var: n1
    - debug:
        var: n2
    - debug:
        var: n2['NEEDRESTART-VER']
    - debug:
        var: n3
    - debug:
        var: n3['NEEDRESTART-VER']
    - debug:
        var: n4
    - debug:
        var: n4['NEEDRESTART-VER']
🌐
GitHub
github.com › ansible › ansible-examples › blob › master › language_features › register_logic.yml
ansible-examples/language_features/register_logic.yml at master · ansible/ansible-examples
February 2, 2019 - # you can use 'stdout_lines' to loop over the registered output lines · - name: motd lines matching 'hi' shell: echo "{{ item }}" with_items: motd_result.stdout_lines · · # you can also split 'stdout' yourself ·
Author   ansible
🌐
Spacelift
spacelift.io › blog › ansible-register
Ansible Register: How to Store and Reuse Task Output
When looping with loop (or with_items), the registered variable stores a list of result objects under your_var.results. Each item includes fields like item, rc, stdout, stderr, and failed. ... This reveals which item failed and why. No, register itself doesn’t meaningfully slow execution; it saves the result Ansible already receives.
Published   October 27, 2025
🌐
Ansible
forum.ansible.com › archives › ansible project
using register stdout_lines in with_items loop - Ansible Project - Ansible
February 22, 2016 - Hello All, I’m ultimately attempting to pull a list of files with wildcarded paths and pass the results into the replace module so it can cycle through them all. However, starting with a more simple example, i’m having issues getting the list of files to print properly in even a simple ...
Top answer
1 of 1
54

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output
🌐
Reddit
reddit.com › r/ansible › how can i register a variable based on the output of a command that is iterated over with_items?
r/ansible on Reddit: How can I register a variable based on the output of a command that is iterated over with_items?
March 24, 2016 -

I have the following playbook:

---
- hosts: cisco
  gather_facts: no
  connection: local
  vars_files:
    - secrets.yaml
    - commands.yaml
 
  tasks:
  - name: DEFINE PROVIDER
    set_fact:
      provider:
        host: "{{ inventory_hostname }}"
        username: "{{ creds['username'] }}"
        password: "{{ creds['password'] }}"
        auth_pass: "{{ creds['auth_pass'] }}"
 
  - name: RUN COMMANDS ON DEVICE
    ios_command:
      provider: "{{ provider }}"
      # transport: cli
      commands:
        "{{ item.command }}"
    register: result
    with_items: "{{ commands }}"

  - debug: var=result.stdout_lines

which references a 'commands.yaml' file that I want the 'RUN COMMANDS ON DEVICE' task to iterate over. The commands.yaml file has a format like:

---
commands:
  - command: show version
  - command: show cdp neighbor

When I run the playbook with -vvv I do see the command output, but I continue to get an error stating that result.stdout_lines is not defined. I've also tried to move the 'register: result' line to below the 'with_items: "{{ commands }}"' line, but that has no effect.

Is there a way for me to iterate of the values in the 'commands.yaml' file and have the output from each 'registered' to a variable that I can later reference?

Thanks.

Top answer
1 of 2
3
Hello there, When you register the result of a loop into a variable, you actually get a list (array) of results. You will need to access the result by the respective index of the item. With the command and shell modules, you actually get the results in a dict key called "results", so it would actually be results.results[0].stdout_lines Here's a sample of what I mean: - hosts: localhost tasks: - shell: "{{ item }}" with_items: - uname -a - hostname - ls -1 /Applications | wc -l register: output - debug: var=output - debug: msg="{{ output.results[0].stdout_lines }}" And the output: PLAY *************************************************************************** TASK [setup] ******************************************************************* ok: [localhost] TASK [command] ***************************************************************** changed: [localhost] => (item=uname -a) changed: [localhost] => (item=hostname) changed: [localhost] => (item=ls -1 /Applications | wc -l) TASK [debug] ******************************************************************* ok: [localhost] => { "output": { "changed": true, "msg": "All items completed", "results": [ { "_ansible_no_log": false, "changed": true, "cmd": "uname -a", "delta": "0:00:00.004952", "end": "2016-03-25 19:19:20.400140", "invocation": { "module_args": { "_raw_params": "uname -a", "_uses_shell": true, "chdir": null, "creates": null, "executable": null, "removes": null, "warn": true }, "module_name": "command" }, "item": "uname -a", "rc": 0, "start": "2016-03-25 19:19:20.395188", "stderr": "", "stdout": "Darwin Fotsies-MBP.gateway 15.4.0 Darwin Kernel Version 15.4.0: Fri Feb 26 22:08:05 PST 2016; root:xnu-3248.40.184~3/RELEASE_X86_64 x86_64", "stdout_lines": [ "Darwin Fotsies-MBP.gateway 15.4.0 Darwin Kernel Version 15.4.0: Fri Feb 26 22:08:05 PST 2016; root:xnu-3248.40.184~3/RELEASE_X86_64 x86_64" ], "warnings": [] }, { "_ansible_no_log": false, "changed": true, "cmd": "hostname", "delta": "0:00:00.004097", "end": "2016-03-25 19:19:20.489036", "invocation": { "module_args": { "_raw_params": "hostname", "_uses_shell": true, "chdir": null, "creates": null, "executable": null, "removes": null, "warn": true }, "module_name": "command" }, "item": "hostname", "rc": 0, "start": "2016-03-25 19:19:20.484939", "stderr": "", "stdout": "Fotsies-MBP.gateway", "stdout_lines": [ "Fotsies-MBP.gateway" ], "warnings": [] }, { "_ansible_no_log": false, "changed": true, "cmd": "ls -1 /Applications | wc -l", "delta": "0:00:00.006134", "end": "2016-03-25 19:19:20.578304", "invocation": { "module_args": { "_raw_params": "ls -1 /Applications | wc -l", "_uses_shell": true, "chdir": null, "creates": null, "executable": null, "removes": null, "warn": true }, "module_name": "command" }, "item": "ls -1 /Applications | wc -l", "rc": 0, "start": "2016-03-25 19:19:20.572170", "stderr": "", "stdout": " 48", "stdout_lines": [ " 48" ], "warnings": [] } ] } } TASK [debug] ******************************************************************* ok: [localhost] => { "msg": [ "Darwin Fotsies-MBP.gateway 15.4.0 Darwin Kernel Version 15.4.0: Fri Feb 26 22:08:05 PST 2016; root:xnu-3248.40.184~3/RELEASE_X86_64 x86_64" ] } PLAY RECAP ********************************************************************* localhost : ok=4 changed=1 unreachable=0 failed=0 I would suggest using with_indexed_items if you wish to iterate across both the list of commands and the respective results e.g. from my macbuild project First the variable: fonts: - url: https://github.com/adobe-fonts/source-code-pro/archive/2.010R-ro/1.030R-it.zip archive: source-code-pro-2.010R-ro-1.030R-it.zip wildcard: '*.otf' creates: SourceCodePro-Regular.otf - url: https://github.com/powerline/fonts/archive/2015-12-04.zip archive: fonts-2015-12-04.zip wildcard: '*Sauce Code Powerline*.otf' creates: Sauce Code Powerline Regular.otf And then the tasks: - name: check if the font is installed stat: path="~/Library/Fonts/{{ item.creates }}" register: font_check with_items: "{{ fonts }}" - name: download the font get_url: url="{{ item.1.url }}" args: dest: /var/tmp mode: 0644 when: not font_check.results[item.0].stat.exists with_indexed_items: "{{ fonts }}" Hope this helps :) Fotis
2 of 2
1
These are very helpful responses. I am having a similar issue, I am trying to search for a string in a variables results. The variable obviously is an array with many results. However, I am trying to write a conditional that only executes the task based on finding a string as it iterates through all of the variable.results.stdout_lines. For example: with_items: "{{ list_of_hashes | default({}) }}" when: "item.hash_string in (variable_array.results.stdout_lines | string)" fgimian's suggestion unfortunately isn't applicable because i need to iterate through all of the items in the variable_array. And nukulaar won't quite work because with_items only takes one variable/list set instead of two like I would need in this scenario. I hope this makes sense... Any help would be lovely!