9

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 if statement in programming languages)?

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 (user_home_result2).

Pseudocode of what I want to do:

- 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: >
      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 }}

Walkaround:

- 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: >
    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 != ''

2 Answers 2

13

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 != ''  
2
11

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.