Score:2

Limit CPU usage Ansible J2 loop

cn flag
raw

I have an Ansible task that formats a list of VLANs. However, when I run the task with multiple forks, it causes my CPU usage to spike to 100% for a long time. How can I optimize the task to reduce CPU usage or limit the CPU usage of this task ?

Here's the original task:

- name: Fromat VLAN list
  ansible.builtin.set_fact:
    device_interface_vlans: "{{ dict(key | zip(val)) }}"
  vars:
    dev_ifc_str: |-
      {% for vlan in ansible_facts.napalm_vlans.keys() %}
      {% for int in ansible_facts.napalm_vlans[vlan]['interfaces'] %}
      - {int: {{ int }}, vlan: {{ nb_vlans | selectattr('vid', 'equalto', vlan | int) | map(attribute='id') | join }}}
      {% endfor %}
      {% endfor %}
    int_vlan: "{{ dev_ifc_str | from_yaml }}"
    arr: "{{ int_vlan | groupby('int') }}"
    key: "{{ arr | map('first') | list }}"
    val: "{{ arr | map('last') |
      map('json_query', '[].vlan') |
      map('community.general.dict_kv', 'vlans') | list }}"

I have already tried cpulimit but it is limiting the cpu usage of each forks and not all of them.

Score:1
cn flag
raw

I fixed it by using json_query wich is wayyyy faster:

    - ansible.builtin.set_fact:
        device_interface_vlans: "{{ dict(key | zip(val)) }}"
      vars:
        dev_ifc_str: |-
          {% for vlan in ansible_facts.napalm_vlans.keys() %}
          {% for int in ansible_facts.napalm_vlans[vlan]['interfaces'] %}
          - {int: {{ int }}, vlan: {{ nb_vlans | json_query('[?vid == `{}`].id'.format(vlan | int)) | join }}}
          {% endfor %}
          {% endfor %}
        int_vlan: "{{ dev_ifc_str | from_yaml }}"
        arr: "{{ int_vlan | groupby('int') }}"
        key: "{{ arr | map('first') | list }}"
        val: "{{ arr | map('last') |
          map('json_query', '[].vlan') |
          map('community.general.dict_kv', 'vlans') | list }}"
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.