想要在 item 的值变为 7 后中断任务,这是示例任务
- hosts: localhost
tasks:
- shell: echo {{ item }}
register: result
with_sequence: start=4 end=16
when: "{{ item }} < 7"
在上面的代码中,它将任务从 4 迭代到 16,如下所示
PLAY [localhost] ***********************************************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [localhost]
TASK [command] *************************************************************************************************************************************************
[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{ item }} < 7
changed: [localhost] => (item=4)
changed: [localhost] => (item=5)
changed: [localhost] => (item=6)
skipping: [localhost] => (item=7)
skipping: [localhost] => (item=8)
skipping: [localhost] => (item=9)
skipping: [localhost] => (item=10)
skipping: [localhost] => (item=11)
skipping: [localhost] => (item=12)
skipping: [localhost] => (item=13)
skipping: [localhost] => (item=14)
skipping: [localhost] => (item=15)
skipping: [localhost] => (item=16)
PLAY RECAP *****************************************************************************************************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0
Ansible 运行循环并且:
对于项目
4
、5
和 6
执行 echo
命令 - 显示 changed
状态,对于剩余项目,它不会执行它 - 显示
skipped
状态,你已经实现了你想要的。
您唯一可以改进的就是通过修复条件来消除警告:
- hosts: localhost
tasks:
- shell: echo {{ item }}
register: result
with_sequence: start=4 end=16
when: "item|int < 7"
没有
break
、until
、when
或任何 IF
、THEN
、ELSE
构造的解决方案。
---
- hosts: localhost
become: false
gather_facts: false
tasks:
- name: "For {{ loop_range }} loop up to < {{ smaller_then }}"
debug:
msg: "{{ item }}"
loop: "{{ loop_range[:idx | int] }}"
loop_control:
extended: true
label: "{{ ansible_loop.index }}"
vars:
smaller_then: 7
loop_range: "{{ range(4, 17, 1) }}"
idx: "{{ loop_range | ansible.utils.index_of('eq', smaller_then) }}"
将导致
TASK [For [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] loop up to < 7] ******
ok: [localhost] => (item=1) =>
msg: 4
ok: [localhost] => (item=2) =>
msg: 5
ok: [localhost] => (item=3) =>
msg: 6