我想有条件地执行一组任务。是否有任何可用的语法可以让我执行一组任务,其中每个整个组都评估一次条件(比如编程语言中的if
语句)?
看一下下面的代码片段。我知道差异很小,但第一个代码更好地表达了我的意图,而没有用额外的变量(user_home_result2
)污染命名空间。
- 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 }}
- 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 != ''
答案 0 :(得分:8)
您可以将任务放在新的yml文件中并使用条件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 }}
在剧本中:
- 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 != ''
答案 1 :(得分:0)
从2.1版开始,ansible具有用于逻辑任务分组的块。块使您只能为几个任务(包括when
条件)指定一次通用的操作。例如:
- 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
以上等同于将when: bool_is_true
附加到块内的两个任务。
更多信息,请访问https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html