How to conditionally execute group of tasks on ansible?

You can put the tasks in a new yml file and use a conditional include:

# subtasks.yml
---
- name: Setting up user {{ user }}
  user: >
    generate_ssh_key=yes
    name="{{ user }}"

- name: Capturing user's home directory
  shell: "getent passwd {{ user }} | awk -F: '{ print $6 }'"
  register: user_home_result

- set_fact: user_home={{ user_home_result.stdout }}

And in the playbook:

- name: Capturing user's home directory
  shell: "getent passwd {{ user }} | awk -F: '{ print $6 }'"
  register: user_home_result

- set_fact: user_home={{ user_home_result.stdout }}

- include: subtask.yml
  when:  user_home != ''  

As of version 2.1, ansible has blocks for logical task grouping. Blocks allow you to specify common things for a few tasks only once, including the when conditionals. Ex:

- block:

    - name: put a file somewhere
      copy: src=asdf dest=asdf

    - name: put another file somewhere
      template: src=asdf.j2 dest=asdf

  when: bool_is_true

The above is equivalent to attaching a when: bool_is_true to both of the tasks inside the block.

More information at https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html

Tags:

Ansible