Way to debug in ansible using register and debug

# tasks file for testing 

- name: check if the container is running
  shell: docker ps | grep "my_mysql"
  register: result
  failed_when: "result.rc == 2"
  check_mode: no

- debug:

- name: check value
  shell: echo "Container is not Running"
  when: result.stdout == ""

The ansible playbook above is what I normally do when it comes to debugging or running the playbook based on some condition match.

Lets write a playbook to check if the container is running or not and we will run the job only when it is running.

  • In line number 5 we are simply running bash script to check if the container with that name is running orĀ  not.
  • In line number 6 we register the variable. This is how we store the result of the command in ansible.
  • The purpose of line number 7 8 is to ignore the error. Suppose if such container is not found in line number 5. Though we expect it to register blank value in our variable. It does not do so and terminate so we are forcing it to ignore the error. On success it returns 0 and 1 on error. So we are making it compare with 2 that will not ever happen and making the playbook not fail.
  • Use debug to check what exactly is there in our registered value. Normally it will showcase everything, here we just want to check output so specifying its key called stdout.
  • Use when to work as a conditional statement in ansible. It is like if condition in any programming language. We want to run the shell command above it only when the value registered output is empty.




Leave a Reply