Loop in ansible task description

115 views Asked by At

I have a requirement I want to use loop to create connector for kafka, I want to use table list in want to use config that will create configs for kafka connectors. for example(this is random example)

- name: Add-user-{{item}} # I want to use varaible in task name 
  ansible.builtin.user:
    name: "{{ item }}"
    state: present
    groups: "wheel"
  loop:
     - testuser1
     - testuser2

Want to use loop in task description

1

There are 1 answers

0
U880D On

The recommended approach would be to use loop with label.

A minimal example playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Example 1
    debug:
      msg: "{{ item }}"
    loop_control:
      label: "Adding user {{ item }}"
    loop:
       - user1
       - user2

will result into an output of

TASK [Example 1] *****************************
ok: [localhost] => (item=Adding user user1) =>
  msg: user1
ok: [localhost] => (item=Adding user user2) =>
  msg: user2

Because it is adding files, complexity, I/O operations to your Use Case, a less recommended approach with include_tasks module – Dynamically include a task list is shown in the following minimal example playbook

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Example 2
    include_tasks: add_user.yml
    loop:
       - user1
       - user2

using a separate task file add_user.yml

- name: Adding user {{ item }}
  debug:
    msg: "{{ item }}"

resulting into an output of

TASK [Example 2] ***********************************************************
included: /home/ansible_user/test/add_user.yml for localhost => (item=user1)
included: /home/ansible_user/test/add_user.yml for localhost => (item=user2)

TASK [Adding user user1] ***************************************************
ok: [localhost] =>
  msg: user1

TASK [Adding user user2] ***************************************************
ok: [localhost] =>
  msg: user2

Documentation and Further Readings