title: How to conditionally execute group of tasks on ansible?
body: <p>I want to conditionally execute a set of tasks. Is there any syntax available that would let me execute a group of tasks, where the condition is evaluated once per whole group (like in a <code>if</code> statement in programming languages)?</p>
  
  <p>Take a look at the code snippets below. I know the difference is small, but the first code better expresses my intention without polluting the namespace with additional variables (<code>user_home_result2</code>). </p>
  
  <h2>Pseudocode of what I want to do:</h2>
  
  <pre><code>- 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 }}
  
  - when:  user_home != ''  
  
    - name: Setting up user {{ user }}
      user: &gt;
        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 }}
  </code></pre>
  
  <h2>Walkaround:</h2>
  
  <pre><code>- 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 }}
  
  - name: Setting up user {{ user }}
    user: &gt;
      generate_ssh_key=yes
      name="{{ user }}"
    when: user_home != ''
  
  - name: Capturing user's home directory
    shell: "getent passwd {{ user }} | awk -F: '{ print $6 }'"
    register: user_home_result2
    when: user_home != ''
  
  - set_fact: user_home={{ user_home_result2.stdout }}
    when: user_home != ''
  </code></pre>