How do you create a directory www
at /srv
on a Debian-based system using an Ansible playbook?
Just need to put condition to execute task for specific distribution
- name: Creates directory
file: path=/src/www state=directory
when: ansible_distribution == 'Debian'
Directory can be created using file module only, as directory is nothing but a file.
# create a directory if it doesn't exist
- file:
path: /etc/some_directory
state: directory
mode: 0755
owner: foo
group: foo
You can directly run the command and create directly using ansible
ansible -v targethostname -m shell -a "mkdir /srv/www" -u targetuser
OR
ansible -v targethostname -m file -a "path=/srv/www state=directory" -u targetuser
---
- hosts: all
connection: local
tasks:
- name: Creates directory
file: path=/src/www state=directory
Above playbook will create www directory in /src path.
Before running above playbook. Please make sure your ansible host connection should be set,
"localhost ansible_connection=local"
should be present in /etc/ansible/hosts
for more information please let me know.
Use file module to create a directory and get the details about file module using command "ansible-doc file"
Here is an option "state" that explains:
If
directory
, all immediate subdirectories will be created if they do not exist, since 1.7 they will be created with the supplied permissions.
Iffile
, the file will NOT be created if it does not exist, see the [copy] or [template] module if you want that behavior.
Iflink
, the symbolic link will be created or changed. Usehard
for hardlinks.
Ifabsent
, directories will be recursively deleted, and files or symlinks will be unlinked.Note that
file
will not fail if the path does not exist as the state did not change.If
touch
(new in 1.4), an empty file will be created if the path does not exist, while an existing file or directory will receive updated file access and modification times (similar to the waytouch
works from the command line).
You want the file module. To create a directory, you need to specify the option state=directory
:
- name: Creates directory
file:
path: /src/www
state: directory
You can see other options at https://docs.ansible.com/ansible/latest/collections/ansible/builtin/file_module.html