DevOps Classroom Series – 13/Oct/2021

Ansible Inventory and Variables Continued

  • Lets start with a use case to install apache and php info on centos 7
sudo yum install httpd -y
sudo systemctl start httpd.service
sudo systemctl enable httpd.service
sudo yum install php php-mysql php-fpm -y
echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php
sudo systemctl restart httpd.service
  • If i have to write a playbook for this it would be some thing like
- name: Install apache and php
  hosts: centos
  become: yes
    - name: install apache
        name: httpd
        state: present
    - name: install php modules
          - php 
          - php-fpm
          - php-mysql 
        state: present
    - name: create info.php
        dest: /var/www/html/info.php
        content: |
        - Restart Apache
    - name: Restart Apache
        name: httpd
        enabled: yes
        state: restarted

  • Our intention is not to have two different files, have one playbook for apache installation for ubuntu & Centos
  • Ideally we should be writing conditional statements
if node is centos
  run centos tasks
else if node is ubuntu
    run ubuntu tasks
  • We should now find out a way of how ansible identifies whether the node is ubuntu or centos & then write conditionals
  • Ansible can collect all the facts(information) about the nodes using the setup module Refer Here
  • Run the following
ansible -i hosts -m setup all


  • Now lets adjust playbooks to use conditionals based on ansible facts Refer Here
  • Refer Here for the changes made to accomodate multiple distributions
  • Lets try to run the playbook Preview Preview Preview
  • The playbook which we have written is supposed to work on ubuntu 20 and centos 7, for this lets try to add multiple conditional statements and ensure our playbook fails on unsupported versions with a message to the user Refer Here for fail module
  • Refer Here for the changes and Refer Here for the conditionals corrected Preview

Leave a Reply

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

About learningthoughtsadmin