DevOps Classroom notes – 15/Nov/2019

Ansible Variable Files

  • Rather than having inventory and variables defined in same file, lets use Variable files.
  • Variable files are of two categories
    • group_vars
    • host_vars
  • Directory Structure should
    • Playbook
    • Inventory
    • group_vars
      • group_name
    • host_vars
      • host_name
  • Lets design the directory structure for the following inventory


  • The directory structure would be
    • lamp.yml
    • hosts
    • group_vars
      • webservers
      • redhat
      • ubuntu
    • host_vars
  • Create files in the group_vars and host_vars
  • Refer this sample over here
  • Lets execute this command
ansible-playbook -i hosts -e package_name=stress lamp.yml

Ansible Variable Precedence

  • Refer Here
  • In majority of Cases variables are defined
    • In Playbook
    • In Inventory
    • In Inventory group_vars and host_vars
    • set fact
    • Roles
    • extra vars

Ansible Special Variables

Adding a custom fail message for unsupported OS

  • After adding a fail message for unsupported os, the playbook looks like
- hosts: webservers
  become: yes
    - name: fail if it is unsupported os
        msg: This playbook is supported only on redhat and debain variants
      when: ansible_facts['os_family'] != "RedHat" and ansible_facts['os_family'] != "Debian"
    - name: install apache
        name: "{{ package_name }}"
        state: present
        - restart and enable apache
    - name: printing php modules
        var: php_modules
    - name: install php modules
        name: "{{ item }}"
        state: present
      loop: "{{ php_modules }}"
    - name: Download info php page
        dest: /var/www/html/info.php
        - restart and enable apache
    - name: restart and enable apache
        name: "{{ package_name }}"
        enabled: yes
        state: restarted

  • In our next series we will cover about
    • files
    • templates
    • Roles
    • set facts (pre and post tasks)
    • Ansible tower

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner