I'm using this command to have a return from tasks in ansible.

To see if they are successful or not.

This is a example of my code in a playbook:

- name: Install JDK8
  shell: cd /tmp/install/ && tar -zxvf jdk-8u51-linux-x64.tar.gz

- name: Echo Install JDK8
  shell: echo $?

When i run the playbook from terminal i do not have any return value.

Can you get a return with the echo command?


Trying to get the $? in the Ansible context you show us, to have the state of success of the last command given to Ansible to execute remotely won't work.

The $? variable is for returning the status of the last command run in the current shell.

In the setup you are showing us you neither have a guarantee the last running command was the one shown in Ansible, nor it is the same shell, and possibly, depending on your ssh client configuration, not even the same ssh session.

Per the example in the Ansible official guide: to do something else if the last executed task/command was successful or not, you do:

  - command: /bin/false
    register: result
    ignore_errors: True

  - command: /bin/something
    when: result is failed

  - command: /bin/something_else
   when: result is succeeded

For further details, see Documentation->Ansible->Conditionals


The two shell commands in your code snipped are executed in different shells, that means ansible will exit the first shell and start a new one for the second command.

If you need the return value of a shell command, it is stored in result.rc:

- name: Install JDK8
  shell: cd /tmp/install/ && tar -zxvf jdk-8u51-linux-x64.tar.gz
  register: result
  ignore_errors: true
- debug:
    msg: "The return value was: {{ result.rc }}"

shell tasks are bad for idempotency, you could try using e.g. the package module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.