
If you are not familiar with modules, check out Ansible - Getting Started with Modules.
The file module with state: directory is used to create a directory. In this example, the /tmp/example directory will be created if it does not exist.
---
- hosts: localhost
tasks:
- name: mkdir /tmp/example
ansible.builtin.file:
path: /tmp/example
state: directory
...
Directory created
If the directory was successfully created, the play should indicate changed.
TASK [mkdir /tmp/example]
changed: [localhost]
Directory not created
If the directory was not created, the play should indicate ok. This is the expected behavior if the directory already exists. If the directory already exists, the directory will not be created, overwritten, or changed.
TASK [mkdir /tmp/example]
ok: [server1.example.com]
Owner / Group / Mode
When the owner, group or mode options are used, if the directory already exists, the directory will be updated with the owner, group and mode.
- name: update /tmp/example owner group mode
file:
path: /tmp/example
state: directory
owner: john.doe
group: admins
mode: "0770"
You may also want to use x.stat.exists to determine if the directory exists, and x.stat.isdir to determine if the object is a directory.
Did you find this article helpful?
If so, consider buying me a coffee over at