Condition, Loops and handlers

Conditions in playbook are same as 'if/else' conditions in programming, use when in Ansible: Syntax:

      tasks:
         - name: Install httpd service Ubuntu
           yum: 
             name: httpd
             state: present
           when: ansible_distribution == 'Ubuntu'
         - name: Install httpd service Centos 
           apt:
             name: httpd
             state: present
           when: ansible_distribution == 'Centos'

Loops

Loops are used to iterate the condition in playbook for diffrent servers.

    tasks:
         - name: Install httpd, git, zip service in Ubuntu
           yum: 
             name: "{{item}}"
             state: present
           when: ansible_distribution == 'Ubuntu'
           loop:
             - httpd
             - git
             - zip
         - name: Install httpd, git, zip service in Centos 
           apt:
             name: "{{item}}"
             state: present
             update_cache: yes
           when: ansible_distribution == 'Centos'
           loop:
             - httpd
             - git
             - zip

Handlers

Sometimes you want a task to run only when a change is made on a machine. For example, you may want to restart a service if a task updates the configuration of that service, but not if the configuration is unchanged.

Ansible uses handlers to address this use case. Handlers are tasks that only run when notified.

---
- name: Verify apache installation
  hosts: webservers
  vars:
    http_port: 80
    max_clients: 200
  remote_user: root
  tasks:
    - name: Ensure apache is at the latest version
      ansible.builtin.yum:
        name: httpd
        state: latest

    - name: Write the apache config file
      ansible.builtin.template:
        src: /srv/httpd.j2
        dest: /etc/httpd.conf
      notify:
      - Restart apache

    - name: Ensure apache is running
      ansible.builtin.service:
        name: httpd
        state: started

  handlers:
    - name: Restart apache
      ansible.builtin.service:
        name: httpd
        state: restarted

Last updated