Ansible - create multiple folders if they do not exist

Goal:

  • Create multiple directories if they do not exist.
  • Do not change permissions of an existing folder

Current play:

- 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 invalid.

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

+5
source share
2 answers

Ansible - create multiple folders without changing the permissions of previously existing ones.

I work great. Hope this works for you, but just give it a 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}}" ... 
+6
source

Using Ansible modules, you do not need to check if something exists or not, you just describe the desired state, therefore:

 - 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
source

Source: https://habr.com/ru/post/1264121/


All Articles