Ansible playbook tips

Ansible playbook tips

Checks :

if a file is present

This task will fail your Ansible playbook if the file doesn't exist and execute the actions under rescue (Here we send an email to admin@domain.com)

tasks:
  - name: Check if we got the generate_report file in /etc/cron.d/ folder
    stat:
      path: /etc/cron.d/generate_report
    register: set_DI_status
    become: yes
    become_method: sudo
    become_flags: -i
    failed_when: set_DI_status.stat.exists == false
    rescue: # Do this if the task fail
     - mail:
         to: admin@domain.com
         subject: Houston, We've Got a Problem
         body: task {{ ansible_failed_task.name }}

Tricks:

Make a playbook executable like a shell script

To make a playbook executable, just add ansible-playbook binary as a shebang.

!/usr/local/bin/ansible-playbook
---
- name: My playbook title
# Your playbook here

And make it executable with chmod +x myPlayBook.yml

Prevent warning

Prevent the warning:

[WARNING]: Platform linux on host yourHost is using the discovered Python interpreter at /usr/bin/python, but future installation of another Python interpreter
could change this. See
https://docs.ansible.com/ansible/2.8/reference_appendices/interpreter_discovery.html for more information.

just add ansible_python_interpreter: /usr/bin/python3 to your script:

---
- hosts: your_specific_host
  vars:
    ansible_python_interpreter: /usr/bin/python3  # Replace with your version.
  tasks:
    # Your tasks go here...