Creating a Directory with Ansible
In this guide, we will demonstrate how to create a directory named www at the path /srv on a Debian-based system using an Ansible playbook. This is a common task when setting up a web server or organizing application files.
Prerequisites
- Ansible installed on your control node.
- Access to a Debian-based target server.
- Basic understanding of Ansible playbook structure.
Ansible Playbook Example
To create the directory, we will utilize the ansible.builtin.file module, which is specifically designed for managing files and directories. Below is an example playbook that accomplishes this task:
---
- name: Create www directory on Debian system
hosts: debian_servers
tasks:
- name: Ensure the /srv/www directory exists
ansible.builtin.file:
path: /srv/www
state: directory
mode: '0755' # Optional: set permissions
Explanation of the Playbook
- hosts: This specifies the group of servers (in this case,
debian_servers) where the playbook will be executed. - tasks: This section contains the actions to be performed on the target servers.
- ansible.builtin.file: This module is used to manage file properties. Here, we specify:
- path: The full path of the directory to create.
- state: Set to
directoryto ensure that the specified path is a directory. - mode: (Optional) Sets the permissions for the directory. In this example,
0755allows the owner to read, write, and execute, while others can read and execute.
Conclusion
Using Ansible to create directories helps maintain consistency across your servers and ensures that the necessary directories are present without manual intervention. This playbook can be easily modified to create additional directories or adjust permissions as needed.