Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - Create multiple folders if don't exist

Tags:

ansible

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   loop: "{{ stat.results }}"   # with_items: "{{ stat.results }}" # for older versions of Ansible   # 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.

like image 469
Kevin C Avatar asked Feb 12 '17 10:02

Kevin C


People also ask

How do you create a directory if not exists in ansible?

If file , the file will NOT be created if it does not exist, see the [copy] or [template] module if you want that behavior. If link , the symbolic link will be created or changed. Use hard for hardlinks. If absent , directories will be recursively deleted, and files or symlinks will be unlinked.

How do I make an ansible folder?

To create a directory using the file module, you need to set two parameters. Path(alias – name, dest) – This is the absolute path of the directory. State – You should give this as 'directory. ' By default, the value is 'file.

Which module will you utilize to create a directory in ansible?

You can use the file module. To create a directory, you need to specify the option state=directory. I have attached one playbook for your reference below.


1 Answers

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   loop:     - /data/directory     - /data/another 
like image 195
techraf Avatar answered Oct 04 '22 15:10

techraf