Ansible: Influencing Action Execution with Conditions and Branches

Ansible Concepts

  • Playbook: A collection of plays
  • Play: A sequence of actions or roles that are applied to a host
  • Action: A concrete command to the host (installing packages, setting config file values)
  • Role: A reusable collection of actions

Run Tasks on Conditions

- name: Set vars when architecture is armv7l
set_fact:
consul_src_file: "consul_{{ consul_version }}_linux_armhfv6.zip"
...
when: ansible_facts.architecture == 'armv7l'
- name: Set vars when architecture is x86_64
set_fact:
consul_src_file: "consul_{{ consul_version }}_linux_amd64.zip"
...
when: ansible_facts.architecture == 'x86_64'
- name: wait for Nginx server to be running
command: /usr/sbin/sync_web_content
wait_for:
path: /var/logs/nginx.pid
state: present

Stop Tasks on Conditions

Validations

- name: Create fstab entry
lineinfile:
path: /etc/fstab
line: "{{ nfs_dir_server_ip }}:{{ nfs_dir_mnt_path }} {{ nfs_dir_mnt_path }} nfs defaults,soft,bg,noauto,rsize=32768,wsize=32768,noatime 0 0"
regex: "{{ nfs_dir_server_ip }}:{{ nfs_dir_mnt_path }}"
state: present
validate: /usr/sbin/mount -fa -T %s

Assertation

- name: Check OS family
assert:
that:
- ansible_facts[inventory_hostname].ansible_os_family == 'Debian'
fail_msg: Host is not Debian, stopping installation

Explicit Fail

- name:
command: consul --version
register: result
failed_when: false
- name: Check if current consul version is installed
fail:
msg: Consul v{{consul_version}} already installed - only updating config files
when: result is search("Consul v{{consul_version}}")

Branching Control Flow with Blocks

- name: Install text editor
block:
- name: Install nano
apt:
name: nano
state: present
- name: Configure nano
template:
src: .nanorc.js
dest: {{user_home}}.nanorc
state: present
when: software_package is defined and software_package == 'nano'
- name: Install zsh
...
- block:
- name:
command: consul --version
register: result
failed_when: false
- name: Check if current consul version is installed
fail:
msg: Consul v{{consul_version}} already installed - only updating config files
when: result is search("Consul v{{consul_version}}")
- name: Get consul binary
...
always:
- name: Copy consul config
template:
src: consul.config.hcl.j2
dest: "{{ consul_base_directory }}/consul.config.hcl"
mode: 0644
notify: Restart consul

Controlling Task Results

- block:
- name:
command: consul --version
register: result
failed_when: false

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store