Loop in Ansible

Page content

Loop

https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html

If you are falifilar with any of program language, you can understand loop in Ansible as iteration like for. while, or etc..

Sample

Loop lines in a file

Answer from Cristian was the answer.

https://stackoverflow.com/questions/33541870/how-do-i-loop-over-each-line-inside-a-file-with-ansible/33544101

directory structure

├── files
│   └── list.txt
└── tasks
    └── main.yml

In tasks/main.yml,

---
- debug:
    msg:  "{{ item }}"
  loop: "{{ lookup('file', 'files/list.txt').splitlines() }}"

In files/list.txt,

This is the first line.
I'm second line.
Last line

Playbook resulst

$ ansible-playbook tasks/main.yml --connection=local
...

TASK [Check_locale : debug] ******************************************************************************
ok: [localhost] => (item=This is the first line.) => {
    "msg": "This is the first line."
}
ok: [localhost] => (item=I'm second line.) => {
    "msg": "I'm second line."
}
ok: [localhost] => (item=Last line) => {
    "msg": "Last line"
}
...

Loop variables

directory structure

├── tasks
│   └── main.yml
└── vars
    └── main.yml

In vars/main.yml,

# TCP keepalive
tcp_kernel_parameters:
- {parameter: "net.ipv4.tcp_keepalive_time",    value:  30}
- {parameter: "net.ipv4.tcp_keepalive_intvl",   value:  15}
- {parameter: "net.ipv4.tcp_keepalive_probes",  value:  3}

In tasks/main.yml,

- name: iteration check.
  loop: "{{ tcp_kernel_parameters }}"
  when: "tcp_kernel_parameters is defined"
  debug:
    msg:  "{{ item.parameter }} hoo {{ item.value }}"