首页 > 解决方案 > Ansible - 当条件不适用于元任务时

问题描述

我似乎在元标记中使用 when 条件时遇到问题。我尝试了一些变化,也做了一些阅读,仍然不确定,所以我想我也会在这里问

任务

- name: "This is my task"
  command: "{{ path to conda }} {{ script }}"
  register: check
  until: check is succeeded
  retries: 5
  no_log: false

- name: "End this play if the script ran successfully on 1 remote target"
  meta: end_play
  when: 
    - check is succeeded

错误

错误!条件检查“检查成功”失败。错误是:失败的测试需要一个字典错误似乎出现在“/path/to/roles/tasks/main.yml”中:第 9 行,第 3 列,但可能在文件中的其他位置,具体取决于确切的语法问题。违规行似乎是:-名称:“如果脚本在 1 个远程目标上成功运行,则结束此播放”^ 此处

更新(为完成而分享)

共享规定的解决方法。在我的用例中,我基本上想在整个库存上“尝试”一项任务,直到成功

最终使用主机变量。如果它是清单中的第一个主机,这将始终尝试该任务,并将“回顾”前一个主机的尝试,然后决定在下一个 inv 主机上再次执行它。

# my task
- name: "Attempt this task on each host if unsuccessful"
  raw: "raw_command_here_as_remote_host_is_using_rbash"
  register: status
  when: >
    inventory_hostname == ansible_play_hosts_all[0] or
    hostvars [ ansible_play_hosts_all [ groups ['my_host_group'].index(inventory_hostname) | int - 1 ] ] ['stop_it'] == 'false'
  ignore_errors: yes
  until: status is succeeded
  retries: 1

- set_fact:
    stop_it: true
    cacheable: yes
  when: status is succeeded

- set_fact:
    stop_it: false
    cacheable: yes
  when: status is not succeeded

标签: ansibleansible-2.x

解决方案


更新(为了完成分享答案)

共享规定的解决方法。在我的用例中,我基本上想在整个库存上“尝试”一项任务,直到成功

最终使用主机变量。如果它是清单中的第一个主机,这将始终尝试该任务,并将“回顾”前一个主机的尝试,然后再决定在下一个 inv 主机上再次执行它。

# my task
- name: "Attempt this task on each host if unsuccessful"
  raw: "raw_command_here_as_remote_host_is_using_rbash"
  register: status
  when: >
    inventory_hostname == ansible_play_hosts_all[0] or
    hostvars [ ansible_play_hosts_all [ groups ['my_host_group'].index(inventory_hostname) | int - 1 ] ] ['stop_it'] == 'false'
  ignore_errors: yes
  until: status is succeeded
  retries: 1

- set_fact:
    stop_it: true
    cacheable: yes
  when: status is succeeded

- set_fact:
    stop_it: false
    cacheable: yes
  when: status is not succeeded

推荐阅读