How to conditionally execute group of tasks on ans

2019-05-10 00:41发布

问题:

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

回答1:

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


标签: ansible