for-loopvariablesansibleiteration

How to keep track of where you are in an Ansible loop?


I need to write some lines in a YAML file for a variable number of times:

- name: Retry a task until a certain condition is met
  lineinfile:
    path: /root/file
    insertafter: '^listeners:'
    line: 'iteration #iteration_number++'
  retries: {{ a_variable }}
  delay: 10

I want to write execution number of each iteration to the file also. Similar to the following for loop:

for i in {1..a_variable}
  do
    echo "i"
  done

How to keep track of where you are in a loop?


Solution

  • Q: "Similar to the following for loop."

    Based on the already given idea, a minimal example playbook

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      tasks:
    
      - name: Echo index into file
        lineinfile:
          path: index.file
          create: true
          line: '{{ item }}'
        loop: "{{ range(1, i + 1, 1) }}"
        loop_control:
          extended: true
          label: "{{ ansible_loop.index }}"
        vars:
          i: 3
    

    will result into an output of

    TASK [Echo index into file] ****
    changed: [localhost] => (item=1)
    changed: [localhost] => (item=2)
    changed: [localhost] => (item=3)
    

    and a file content of

    cat index.file
    1
    2
    3
    

    Even if this is technically possible one should keep in mind The Zen of Ansible.

    If you're trying to "write code" in your plays and roles, you're setting yourself up for failure. Ansible's YAML-based playbooks were never meant to be for programming.

    Documentation