ansible

Ansible - Create multiple folders if don't exist


Goal:

- name: stat directories if they exist
  stat:
    path: "{{ item }}"
  loop:
    - /data/directory
    - /data/another
  register: myvar

- debug:
    msg: "{{ myvar.results }}"

- name: create directory if they don't exist
  file:
    path: "{{ item.invocation.module_args.path }}"
    state: directory
    owner: root
    group: root
    mode: 0775
  loop: "{{ stat.results }}"
  when: not myvar.results.stat.exists

The when statement is wrong.

I looked at the example provided. But this only works for a single folder.


Solution

  • Using Ansible modules, you don't need to check if something exist or not, you just describe the desired state, so:

    - name: create directories if they don't exist
      file:
        path: "{{ item }}"
        state: directory
        owner: root
        group: root
        mode: 0775
      loop:
        - /data/directory
        - /data/another