Ansible: Selections

Ansible: Selections

Let's continue a talk about control structures in Ansible. Now, when we know how to imitate subroutines, it is time to discuss selections - if-then-else and case/switch operators.

Ansible offers conditional execution for single tasks,  task blocks,  and task imports. In addition, it allows effectively simulate if-then selection. Let's take a look at the pseudocode below:

- hosts: localhost
  vars:
    true_var: yes
  tasks:
    - debug: 
        msg: "It's true!"
      when: true_var|bool    
 
Task condition

   Ansible has no else-elseif clauses, but you can easily substitute them, like the following code snippet.

- hosts: localhost
  vars: 
    true_var: yes
  tasks:   
    - debug:
        msg: "It's true!"
      when: true_var|bool
    - debug: 
        msg: "No it's not!"
      when: not true_var|bool  
If-then-else Simulation

Naturally, you can build quite a complex combination using multiple conditions and combining tasks, even simulate switch operator. Yet, Ansible offers a rather elegant way to implement switch selectors.  

- hosts: localhost
  tasks:
    - include_tasks:
         file: "run-{{ selector |default('default') }}-tasks.yml" 
Switch Operator 

The code above uses a variable selector to identify which file to import into your play. If the variable is not defined, the task will use 'run-default-tasks.yml' as a file name. Thus, you can create multiple files for import, one for each option you want to handle.

Ansible offers another and very powerful mechanism to execute a part of your code - tags. Specifying tags to include or exclude at runtime you can completely change the playbook behavior. You can check my previous post to find more details.