3

I'm starting to learn ansible and trying to create some directories that will be used in different tasks in the playbook so I create variables for each one.

My playbook so far.

---
- name: tests
  hosts: all
  vars:
    dir1: /data/dir1
    dir2: /mnt/dir2
  tasks:
    - debug:
        msg: "{{ item }}"
      loop:
        - "{{ dir1 }}"
        - "{{ dir2 }}"
    - name: create directories
      file:
        path: "{{ item }}"
        state: directory
        mode: '0755'
        loop:
          - "{{ dir1 }}"
          - "{{ dir2 }}"

The debug works as expected but I get this error

The task includes an option with an undefined variable. The error was: 'item' is undefined

Also tried

    - name: create directories
      file:
        path: "{{ item }}"
        state: directory
        mode: '0755'
        with_items:
          - "{{ dir1 }}"
          - "{{ dir2 }}"

Using Ansible 2.9.6 on Ubuntu 20.04 LTS on Raspberry Pi 4

CJZ
  • 33
  • 3

1 Answers1

2

Q: 'item' is undefined

A: The indentation of loop is wrong (with_items the same). Fix the syntax

    - name: create directories
      file:
        path: "{{ item }}"
        state: directory
        mode: '0755'
      loop:
        - "{{ dir1 }}"
        - "{{ dir2 }}"

Probably Ansible checks the variables before the parameters of a module. This might be the reason Ansible fails with 'item' is undefined instead of 'loop' unknown parameter of the module file.

Vladimir Botka
  • 27,477
  • 4
  • 17
  • 32