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
- zipHandlers
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.
Last updated