On Thu, 30 Jan 2020 08:24:14 -0800 (PST)
Eric S <[email protected]> wrote:

> So far, I have a playbook that I can use to get a list of CPU values. 
> However, I am having trouble correlating the value of CPU to its 
> corresponding hostname.
> 
> ---
> - hosts: host_list
>   gather_facts: false
> 
>   tasks:
>   - name: Get CPU usage
>     shell: "top -b -n 1 | head -n3 | tail -n1 | awk '{print $2}'"
>     register: top
> 
>   - name: Set CPU fact
>     set_fact:
>       cpu_list: "{{ ansible_play_hosts | map('extract', hostvars, 'top') | 
> map(attribute='stdout') | list }}"

Create list of dictionaries

  - name: Set CPU fact
    set_fact:
      cpu_list: "{{ ansible_play_hosts|
                     map('extract', hostvars)|
                     list|
                     json_query('[].{host: inventory_hostname,
                                     cpu: top.stdout}') }}"
    run_once: true

Find the minimal load

  - set_fact:
      cpu_min: "{{ cpu_list|json_query('[].cpu')|min }}"
    run_once: true

and find the host with this minimal load

  - set_fact:
      host_min: "{{ cpu_list|json_query(query)|first }}"
    vars:
      query: "[?cpu == '{{ cpu_min }}'].host"
    run_once: true

HTH,

        -vlado

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20200130190759.0e7f8dfb%40gmail.com.

Attachment: pgpDN87lhIIX5.pgp
Description: OpenPGP digital signature

Reply via email to