模块介绍

ansible.builtin.pause 模块用于在 Ansible Playbook 执行过程中暂停一段时间,或者等待用户确认后继续执行。该模块适用于 Linux 和 Windows 目标主机。

参数

  • minutes(字符串):暂停的分钟数,必须为正数。
  • seconds(字符串):暂停的秒数,必须为正数。
  • prompt(字符串):自定义提示信息,默认为“Pausing for X seconds”。
  • echo(布尔值):是否回显用户输入,默认为 no。

默认行为

  • 如果未指定 minutes 或 seconds,默认会显示一个提示框,等待用户手动确认。
  • 如果指定了时间(minutes 或 seconds),用户输入将被忽略,且不会回显任何内容。
  • 从 Ansible 2.2 开始,如果指定的时间为 0 或负数,将默认等待 1 秒(而不是无限期等待)。

示例:暂停 Playbook 执行

代码文件: pause.yml

---
- name: pause module demo
  hosts: all
  vars:
    wait_seconds: 10
  tasks:
    - name: pause for {{ wait_seconds | int }} second(s)
      ansible.builtin.pause:
        seconds: "{{ wait_seconds | int }}"

    - name: message
      ansible.builtin.debug:
        msg: "The end"

执行结果

  1. 正常执行

    bash $ ansible-playbook -i demo/inventory pause/pause.yml PLAY [pause module demo] ********************************** TASK [Gathering Facts] ************************************ ok: [demo.example.com] TASK [pause for 10 second(s)] ***************************** Pausing for 10 seconds (ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort) ok: [demo.example.com] TASK [message] ********************************************* ok: [demo.example.com] => { "msg": "The end" } PLAY RECAP ************************************************* demo.example.com : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

  2. 手动继续(Ctrl+C + "C")

    bash $ ansible-playbook -i demo/inventory pause/pause.yml PLAY [pause module demo] ********************************** TASK [Gathering Facts] ************************************ ok: [demo.example.com] TASK [pause for 10 second(s)] ***************************** Pausing for 10 seconds (ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort) Press 'C' to continue the play or 'A' to abort ok: [demo.example.com] TASK [message] ********************************************* ok: [demo.example.com] => { "msg": "The end" }

  3. 手动终止(Ctrl+C + "A")

    bash $ ansible-playbook -i demo/inventory pause/pause.yml PLAY [pause module demo] ********************************** TASK [Gathering Facts] ************************************ ok: [demo.example.com] TASK [pause for 10 second(s)] ***************************** Pausing for 10 seconds (ctrl+C then 'C' = continue early, ctrl+C then 'A' = abort) Press 'C' to continue the play or 'A' to abort fatal: [demo.example.com]: FAILED! => {"msg": "user requested abort!"} NO MORE HOSTS LEFT *************************************** PLAY RECAP ************************************************* demo.example.com : ok=1 changed=0 unreachable=0 failed=1 skipped=0 rescued=0 ignored=0

使用场景

  • 调试 Playbook:在执行过程中暂停,检查中间状态。
  • 等待用户确认:在关键操作前等待用户确认,避免误操作。
  • 模拟延时:在测试环境中模拟真实场景的延时。

注意事项

  • 如果同时指定 minutes 和 seconds,两者的时间会相加。
  • 如果需要用户输入,建议使用 prompt 参数自定义提示信息,以提高可读性。

通过 ansible.builtin.pause 模块,你可以灵活地控制 Playbook 的执行流程,使其更加符合实际需求。