Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

ansible loop include_tasks and until success

I would like to know how to loop over multiple tasks until condition is met.

#main.yml

  - set_fact:
      num: 1
      req_num: 10

  - name:  Start to unregister entities
    include_tasks: output.yml
    loop: "{{ range(num, req_num + 1)|list }}"

#output.yml

  - name: get status
    raw: cat /tmp/output
    register: rawoutput

  - name: copy to localhost
    copy:
      content: "{{rawoutput.stdout}}"
      dest: /tmp/output1
    delegate_to: localhost

  - name: reg output2
    shell: awk something /tmp/output1 |awk '/something/,0' |head -n something |tail -n something > /tmp/output2 ; cat /tmp/output2
    register: output2
    delegate_to: localhost

  - name: compare output2
    debug:
      msg: "{{item}}"
    with_items: "{{ output2.stdout_lines }}"
    until: item == "Synced"
    retries: 2
    delay: 2

#cat /tmp/output2

Synced
Syncing
Synced
Failed

I am using this, but the playbook quits when the subtask fail.

My goal is to make sure all the content from output2 is "Synced", loop output.yml until the result is "Synced", or failed after x attempts.

Appreciate if there is better way of doing this. thanks Thanks

question from:https://stackoverflow.com/questions/65914952/ansible-loop-include-tasks-and-until-success

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think I found my answer here.

from ovski4

- name: 'Wait until success'
  block:
    - name: Set the retry count
      set_fact:
        retry_count: "{{ 0 if retry_count is undefined else retry_count|int + 1 }}"

    - name: Get server updated ip
      uri:
        url: https://localhost/ip
        return_content: yes
        status_code: 200
      register: ip

    - name: ssh to the server
      wait_for:
        host: "{{ ip }}"
        port: 22
        timeout: 30
        state: started
  rescue:
    - fail:
        msg: Ended after 5 retries
      when: retry_count|int == 5

    - debug:
        msg: "Failed to connect - Retrying..."

    - include_tasks: wait_until_success.yml

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...