Ansible Debug: Print Variable & List All Variables – Playbook

During Ansible playbook debugging it is useful to know how to display host facts or registered variables.

To print a message from Ansible playbook, as well as a value of a variable, we can use Ansible debug module.

In the examples below i am showing how to print particular Ansible variables and how to list all known facts and variables from Ansible playbook.

Cool Tip: Enable DEBUG mode and increase VERBOSITY in Ansible! Read more →

Debug Ansible Playbook by Printing Variables

Print a variable:

- name: "Ansible | Print a variable"
  debug:
    msg: "The operating system is {{ ansible_distribution }}"

Display a variable only if it is defined:

- name: "Ansible | Print a variable if defined"
  debug:
    msg: "The 'foo' variable value is {{ foo }}"
  when: foo is defined

- name: "Ansible | Print a message if a variable is undefined"
  debug:
    msg: "The 'bar' variable is undefined"
  when: bar is not defined

Print multiple variable:

- name: "Ansible | Print multiple variable"
  debug:
    msg: |
      The role is {{ host_role }}
      The environment is {{ host_environment }}

List all known variables and facts:

- name: "Ansible | List all known variables and facts"
  debug:
    var: hostvars[inventory_hostname]
Was it useful? Share this post with the world!

2 Replies to “Ansible Debug: Print Variable & List All Variables – Playbook”

  1. To also print the “magic variables”, print the variable “vars”
    from https://stackoverflow.com/questions/18839509/where-can-i-get-a-list-of-ansible-pre-defined-variables

    “`yaml
    – name: print magic vars
    debug:
    var: vars
    “`

  2. This is great. My question might be simple, but I can’t find it anywhere. Can you output all those facts and variables separately?

    I’ll give you a use case, and maybe you have a better idea for the solution. I’m using roles and sometimes calling roles from other roles, and using include_files and include_tasks, and also occasionally calling jinja2 files! (breath) So it would be very helpful troubleshooting all this if it was possible to see facts v. variables.

    If you have a magic wand, extra credit would be if you can identify the level of precedence where the variable was defined. I know, I know, like I said it’s extra credit! 🙂

    Thanks.

Leave a Reply