Improve Ansible Performance

Viewed 171

I'm attempting to improve the performance for ansible playbooks. I have a test playbook as follows:

---
- name: Test
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: Creating an empty file
      file:
        path: /tmp/hello
        state: touch

    - name: Test
      command: "echo 'Hello, World!' >> /tmp/hello"
      with_sequence: start=1 end=500
      delegate_to: localhost

Running this takes a whopping 57 seconds. Comparing to a bash script doing the same thing:

test.sh

#!/bin/bash
touch /tmp/hello
for i in {1..500}
do
  sh /home/admin/hello.sh
  echo "This is iteration $i"
done

hello.sh

#!/bin/bash
echo "Hello, World!" >> /tmp/hello

That takes ~1.5 seconds to run.

I have already made some changes to ansible.cfg file

[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=18000s -o PreferredAuthentications=publickey
control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r
pipelining = True

Is there anything else I can do to improve this abysmal performance?

1 Answers

With your code, ansible will connect 500 times to the host to run a command. You could create your desired file first, and then upload it to the host.

playbook.yml

---
- name: Test
  hosts: localhost
  connection: local
  gather_facts: false
  tasks:
    - name: create 'hello' file
      ansible.builtin.template:
        src: "../templates/hello.j2"
        dest: "/tmp/hello"

hello.j2

{% for i in range(500) %}
Hello, World!
{% endfor %}
Related