tech:notes_ansible_boucle_loop
Différences
Ci-dessous, les différences entre deux révisions de la page.
| Les deux révisions précédentesRévision précédente | |||
| tech:notes_ansible_boucle_loop [2025/11/11 17:32] – Jean-Baptiste | tech:notes_ansible_boucle_loop [2026/06/07 19:12] (Version actuelle) – modification externe 127.0.0.1 | ||
|---|---|---|---|
| Ligne 1: | Ligne 1: | ||
| + | < | ||
| + | {{tag> | ||
| + | |||
| + | # Notes Ansible boucle loop | ||
| + | |||
| + | Exemple équivalent à une boucle for imbriqué dans une boucle for, grâce au filtre `product` | ||
| + | |||
| + | ~~~yaml | ||
| + | #! / | ||
| + | |||
| + | - name: play test loop | ||
| + | hosts: localhost | ||
| + | |||
| + | vars: | ||
| + | objects: | ||
| + | - pomme | ||
| + | - banane | ||
| + | |||
| + | emails: | ||
| + | - ' | ||
| + | - ' | ||
| + | |||
| + | tasks: | ||
| + | - name: Exemple boucle | ||
| + | debug: | ||
| + | msg: "{{ object }} - {{ email }}" | ||
| + | vars: | ||
| + | object: "{{ item.0 }}" | ||
| + | email: "{{ item.1 }}" | ||
| + | loop: "{{ objects | product(emails) | list }}" | ||
| + | ~~~ | ||
| + | |||
| + | ~~~javascript | ||
| + | ok: [localhost] => (item=[' | ||
| + | " | ||
| + | } | ||
| + | ok: [localhost] => (item=[' | ||
| + | " | ||
| + | } | ||
| + | ok: [localhost] => (item=[' | ||
| + | " | ||
| + | } | ||
| + | ok: [localhost] => (item=[' | ||
| + | " | ||
| + | } | ||
| + | ~~~ | ||
| + | |||
| + | |||
| + | |||
| + | |||
| + | ## Ansible loop break | ||
| + | |||
| + | ~~~yaml | ||
| + | # | ||
| + | --- | ||
| + | |||
| + | - name: test | ||
| + | hosts: localhost | ||
| + | |||
| + | tasks: | ||
| + | - name: break 1 | ||
| + | command: "echo {{ item }}" | ||
| + | register: res | ||
| + | with_sequence: | ||
| + | when: | ||
| + | - item | int > 3 | ||
| + | - not (res.changed | d(false)) | ||
| + | |||
| + | - name: break 2 | ||
| + | set_fact: | ||
| + | id: "{{ item }}" | ||
| + | register: res2 | ||
| + | with_sequence: | ||
| + | # Because set_fact not make " | ||
| + | changed_when: | ||
| + | when: | ||
| + | - not (res2.changed | d(false)) | ||
| + | # Ca fonctionne mais | ||
| + | # * hélas ce n'est pas un vrai Break car il boucle sur toutes les valeurs | ||
| + | # * plus problématique encore, ce n'est pas idempotent, car il fait un " | ||
| + | |||
| + | # Nous préférerons utiliser les listes | ||
| + | - name: break 3-A | ||
| + | set_fact: | ||
| + | ids: "{{ ids | d([]) + [ item | int ] }}" | ||
| + | with_sequence: | ||
| + | when: item | int > 3 | ||
| + | |||
| + | - name: break 3-B | ||
| + | debug: | ||
| + | msg: "{{ ids | min }}" | ||
| + | ~~~ | ||
| + | |||
| + | |||
| + | |||
| + | |||
