Closed markgraf closed 1 year ago
I've just tried this, using this code:
- name: Experiment
hosts: localhost
become: no
gather_facts: no
vars:
messages: []
# - First
# - Second
# - Third
tasks:
- name: Show a message
ansible.builtin.debug:
msg: "Message: {{ item }}"
loop: "{{ messages }}"
when:
- "{{ messages | length > 0 }}"
I could not measure differences, as Ansible skips a task when the looped list is empty.
Can you, sort of, show me the performance gain?
You will only see the performance gain if you try this with ansible.builtin.package
.
We're not looping, but passing the module an empty list. And on getting an empty list, it will still update the package cache, at least on RHEL. I noticed that when a disfunct internal repo took ages to update and the role got stuck, even though no installation was needed. (What a way to find out about a broken service :-/ )
So with this playbook
---
- name: Dummy Playbook
hosts: localhost
connection: local
become: yes
gather_facts: no
vars:
package_list: []
tasks:
- name: Install empty list of packages
ansible.builtin.package:
name: "{{ package_list }}"
state: present
- name: Skip empty list of packages
ansible.builtin.package:
name: "{{ package_list }}"
state: present
when: package_list | length > 0
You will see that the play pauses a few seconds on "Install empty list of packages", while it just skips it on "Skip empty list of packages". 5 seconds gained on the host I just tried it on.
And those 5 seconds add up when you add users to a fleet of hosts with scheduled playbook-runs every morning.
PLAY [Dummy Playbook] ***************************************************************************************************
TASK [Install empty list of packages] ***********************************************************************************
task path: /home/markgraf/ansible/playbooks/helpers/dummy.yml:13
ok: [localhost] => {
"changed": false,
"rc": 0,
"results": []
}
MSG:
Nothing to do
TASK [Skip empty list of packages] ***********************************************************************************
task path: /home/markgraf/ansible/playbooks/helpers/dummy.yml:18
skipping: [localhost] => {
"changed": false,
"skip_reason": "Conditional result was False"
}
PLAY RECAP **************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
The variable "users_requirements" is an empty list by default. The task will still needlessly check for updates though. Skipping this when it is not needed speeds up the playbook run.
name: Pull request about: Describe the proposed change
Describe the change Add condition to skip "Install required software" if there is none to be installed.
Testing Successfully ran the role without installing an empty list of packages.