如何让Ansible Role重复执行直至满足指定条件
Ansible重复调用Role直至满足条件失败问题
我有一个用于获取网络交换机信息的Ansible Role,返回数据格式如下:
"networkSwitch": [ { "switchName": "some_switch_name_01", "uplinks": [ "physicalNic-nic0", "physicalNic-nic3" ], "uplink_count": 2 } ]
需求
需要重复调用该Role,直至满足以下两个条件之一(优先同时满足):
- switchName值与预期名称匹配
- uplink_count >= 1
尝试过程与问题
发现include_role或retry_role无法使用until/retry/delay参数,于是尝试通过循环任务组的方式实现,创建了get_switch_detail.yml文件,内容如下:
--- - name: repeat until success block: - name: increment attempts counter set_fact: attempt_number: "{{ attempt_number | d(0) | int + 1 }}" - name: Get switch details debug: msg: "This is a dummy task, it doesn't actually get the switch details" - name: Print the switch facts debug: var=item with_items: "{{switch_facts.results}}" when: item.ansible_facts is defined - name: set fact to collect specific Switch attributes set_fact: networkSwitch: "{{ networkSwitch | d([]) + [{ 'switchName': item.ansible_facts.config.network.proxySwitch[0].dvsName, 'uplinks': item.ansible_facts.config.network.proxySwitch[0].pnic, 'uplink_count': item.ansible_facts.config.network.proxySwitch[0].pnic|length }] }}" with_list: "{{lookup('list', switch_facts.results) }}" when: item.ansible_facts is defined - name: Print the proxySwitch attributes debug: msg: - "proxySwitch attributes are: {{proxySwitch}}" - "proxySwitch name is: {{proxySwitch[0].dvsName}}" - "Number of proxySwitch uplinks is: {{proxySwitch[0].pnic_count}}" - name: Print debug: var=proxySwitch - name: Task to check for success debug: msg: success when: - proxySwitch[0].switchName == target_switch_name - proxySwitch[0].uplink_count >= 2 rescue: - name: "Fail if we reached the max of {{ max_attempts | d(3) }} attempts" # Default will be 3 attempts if max_attempts is not passed as a parameter ansible.builtin.fail: msg: Maximum number of attempts reached when: attempt_number | int == max_attempts | int | d(3) - ansible.builtin.debug: msg: "group of tasks failed on attempt {{ attempt_number }}. Retrying" - name: add delay if needed # no delay if retry_delay is not passed as parameter ansible.builtin.wait_for: timeout: "{{ retry_delay | int | d(omit) }}" when: retry_delay is defined # include ourselves to retry. - ansible.builtin.include_tasks: ../get_switch_detail.yml
通过以下方式调用该文件:
- name: Retrying include_tasks: ../get_switch_detail.yml vars: max_attempts: 4 retry_delay: 5
但任务从未重复执行,寻求解决方案。
内容的提问来源于stack exchange,提问作者piercjs
相关产品推荐
相关产品推荐

