Search code examples
linuxansibleansible-inventory

Ansible - starting a task after cpu load is below 2.0


I am trying to create a playbook where I want to perform a simple debug task after cpu load is below 2.0.

I have this so far in cpu-load.yml:

---
- name: Check CPU load and wait
  hosts: localhost
  gather_facts: yes
  
  tasks:
    - name: Check cpu load
      shell: uptime | awk -F 'load average:' '{print $2}' | awk -F ', ' '{print $1}'
      register: cpu_load
      
    - name: Wait until cpu load is bellow 2.0
      wait_for:
        timeout: 300
        delay: 10
        shell: Do something here
        msg: "cpu load is bellow 2.0"
      
    - name: Continue jobs
      debug:
        msg: "CPU load is bellow 2.0. Continue!!!"

Now I am not sure how to make the task wait for the cpu load to go bellow 2.0. Can you guys help?


Solution

  • You need to put an until loop around your "check cpu load" task:

    - hosts: localhost
      gather_facts: false
      tasks:
        - name: Check cpu load
          shell: uptime | awk -F 'load average:' '{print $2}' | awk -F ', ' '{print $1}'
          register: cpu_load
          until: cpu_load.stdout|float < 2.0
          retries: 300
          delay: 1
    
        - name: Some other task
          debug:
            msg: hello world
    

    This will wait up to five minutes (300 retries with a 1-second delay) for the load average to drop below 2.0.


    There are probably better ways to get the current 1-minute CPU load; reading from /proc/loadavg may be easiest:

    - hosts: localhost
      gather_facts: false
      tasks:
        - name: Check cpu load
          command: cat /proc/loadavg
          register: cpu_load
          until: cpu_load.stdout.split()|first|float < 2.0
          retries: 300
          delay: 1
    
        - name: Some other task
          debug:
            msg: hello world