Ansible - Create multiple folders if don't exi

2019-03-15 08:08发布

问题:

Goal:

  • Create multiple directories if they don't exist.
  • Don't change permissions of existing folder

Current playbook:

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

- debug: var=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
  with_items: "{{ stat.results }}"
  # when: myvar.results.stat.exists == false

The when statement is wrong.

I looked at the example provided; http://docs.ansible.com/ansible/stat_module.html. But this only works for a single folder.

回答1:

Ansible - Creating multiple folders without changing permissions of previously existing.

Working fine for me. Hope this works for you as well just try.

---
- name: "Creating multiple by checking folders"
  hosts: your_host_name
  tasks:
  - block:
    - name: "Checking folders"
      stat:
       path: "{{item}}"
      register: folder_stats
      with_items:
      - ["/var/www/f1","/var/www/f2","/var/www/f3","/var/www/f4"]
    - name: "Creating multiple folders without disturbing previous permissions"
      file:
       path: "{{item.item}}"
       state: directory
       mode: 0755
       group: root
       owner: root
      when: item.stat.exists == false
      with_items:
      - "{{folder_stats.results}}"
...


回答2:

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

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


回答3:

My answer may not work in every case, but if you don't supply an option, ansible won't change the current values. I've used this for NFS mounts where permissions vary on the NFS servers.

- name: create directory if they don't exist
  file:
    path: "{{ item }}"
    state: directory
  with_items:
    - /share1
    - /share2


标签: ansible