You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Ansible Playbook,在CPU负载低于2.0后执行任务?

解决Ansible等待CPU负载低于2.0的问题

你的需求是等待CPU负载降至2.0以下再执行后续任务,原Playbook里的wait_for模块用法有误,下面提供三种可行的实现方式:

方式一:利用until循环(推荐,逻辑直观)

直接在CPU负载检查任务上添加循环配置,重复执行检查直到负载达标,无需单独的wait_for任务:

---
- name: Check CPU load and wait
  hosts: localhost
  gather_facts: yes
  
  tasks:
    - name: Wait until CPU load is below 2.0
      shell: uptime | awk -F 'load average:' '{print $2}' | awk -F ', ' '{print $1}'
      register: cpu_load
      until: cpu_load.stdout | float < 2.0
      retries: 30  # 30次重试 × 10秒间隔 = 300秒超时,和原配置一致
      delay: 10
      changed_when: false  # 标记此任务无系统状态变更

    - name: Continue jobs
      debug:
        msg: "CPU load is below 2.0. Continue!!!"

关键参数说明:

  • until:定义循环终止条件,将shell输出转为浮点数后判断是否小于2.0
  • retries:最大重试次数,结合delay控制总超时时间
  • changed_when: false:避免每次执行shell命令都被标记为"changed"状态

方式二:使用wait_for模块结合测试命令

wait_for模块支持通过test参数执行系统命令判断条件,命令返回0时终止等待:

---
- name: Check CPU load and wait
  hosts: localhost
  gather_facts: yes
  
  tasks:
    - name: Wait until CPU load is below 2.0
      wait_for:
        timeout: 300
        delay: 10
        test: "`uptime | awk -F 'load average:' '{print $2}' | awk -F ', ' '{print $1}'` < 2.0"
        msg: "Timeout reached: CPU load never dropped below 2.0"

    - name: Continue jobs
      debug:
        msg: "CPU load is below 2.0. Continue!!!"

说明:

  • test参数内的命令需用反引号包裹,让shell执行后返回结果进行数值比较
  • 若300秒内负载未达标,会抛出msg中定义的错误信息

方式三:利用Ansible内置facts(无需额外shell命令)

你已开启gather_facts: yes,Ansible会自动收集系统负载数据,直接调用ansible_facts.load_avg变量即可:

---
- name: Check CPU load and wait
  hosts: localhost
  gather_facts: yes
  
  tasks:
    - name: Wait until CPU load is below 2.0
      set_fact:
        current_load: "{{ ansible_facts.load_avg[0] | float }}"
      until: current_load < 2.0
      retries: 30
      delay: 10

    - name: Continue jobs
      debug:
        msg: "CPU load is below 2.0. Continue!!!"

说明:

  • ansible_facts.load_avg是列表类型:load_avg[0]对应1分钟平均负载,load_avg[1]是5分钟,load_avg[2]是15分钟,可按需选择
  • 无需调用外部命令,效率更高且更可靠

内容的提问来源于stack exchange,提问作者fr0zt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:03:12