Marvelous
Marvelous

Reputation: 361

Skipping item from loop

I want ansible loop to skip first only the first item on a list > item - a

the task looks like:

- name: create project sub-directory
  win_file:
    path: '{{ projects_dir }}\{{ project_name }}\{{ item }}'
  state: directory
  loop: '{{ sub_directories }}'

vars file looks like:

sub_directories:
 - a
 - b
 - c
 - d

I want the loop to skip item - a so that it creates only b, c and d subdirectories.

Upvotes: 3

Views: 3552

Answers (3)

neuhaus
neuhaus

Reputation: 4094

For the record, here is another solution specifically for special handling of the first item:

Set loop_control to extended and then utilize the ansible_loop.first variable set by ansible for the first item of the loop.

This requires Ansible 2.8 or later.

Upvotes: 0

Vladimir Botka
Vladimir Botka

Reputation: 68034

Use index. See Lists

loop: "{{ sub_directories[1:] }}"

Upvotes: 6

Smily
Smily

Reputation: 2568

You can use loop control in ansible

- name: create project sub-directory
  win_file:
    path: '{{ projects_dir }}\{{ project_name }}\{{ item }}'
  state: directory
  when: my_idx != 0
  loop: '{{ sub_directories }}'
  loop_control:
     index_var: my_idx 

Upvotes: 2

Related Questions