Ansible

Working With Directories in Ansible

Ansible is a handy tool for efficiently managing resources over a network of devices. It provides various options to users, all in one package. This includes multiple automation options and data configuration. The main components of ansible are tiny programs that perform specific tasks on a system. These are called modules, and Ansible has many of them (more than 800). So, in this article, we go over how we can install Ansible and use it to create a new directory if one does not already exist. So without further ado, let us dive into it.

Install Ansible

First, we install Ansible if it is not already installed on our systems. To Install Ansible, follow the steps given below. Skip to the next part if Ansible is already installed.

First and foremost, we update our system so that all packages are up to date and no issues are encountered while installing the dependencies for Ansible. To update the system, we type in the following command.

$ sudo apt update && sudo apt upgrade

Next, we install some packages that are the prerequisites for installing Ansible. To install these packages, type in the following command.

$ sudo apt install software-properties-common python3 python3-pip python3-dev sshpass apt-transport-https ca-certificates libffi-dev libkrb5-dev libcurl4-openssl-dev libssl-dev

Finally, we can install Ansible and check its version using the following set of commands.

$ sudo -H pip3 install ansible

And lastly:

ansible --version

Now that we have Ansible installed, we need a playbook to write scripts that will automate our day-to-day tasks. A simple text editor like Vim should do as it does not consume a lot of memory and supports the “YAML” format in which Ansible scripts are written.

Now let us turn to the problem at hand, creating a new directory in Ansible if it does not already exist. We will describe the basics of a directory and explain how we can make new directories on Ansible with a few examples.

What is a Directory?

A directory is a location that organizes and stores files on a computer. You can think of it as a roadmap that shows the content stored and its exact location and division. It helps the user navigate the files in the system by designating a specific path for each file we have on our system.

This useful mechanism helps keep our system organized without causing issues. For instance, imagine you have two games, pinball1 and pinball2. These games have their directories with their saved data containing all player progress in the two games. If there were no directories to distinguish both the games, the “save data” folder would always be overwritten by the game that was played last, losing all previous data.

Difference Between a File and a Directory

Files and directories are two different terms. A directory is a specific area in computer memory containing other subdirectories and files. On the other hand, a file can be stored in a directory and contains information used by the system for running various applications. It should also be noted that a file has an extension, whereas a directory does not.

Make a Directory in Ansible

We may make a directory on Ansible by using the file module. This module is used to manage symlinks, directories, and files. It also has other features like imposing file and directory ownership and permissions. All these tasks are performed on the remote hosts. An example shown below explains how a new directory is made in Ansible if it does not exist.

- name: directory demonstration
  file:
    path: /src/newdirectory
    state: directory
    owner: root
    group: root
    mode: 0775

You can run playbooks with the help of the following command:

ansible-playbook testbook.yml

The script above makes a new directory named “new director” with path /etc/newdirectory. The mode is a parameter of the file module that indicates the owner and group of the directory may execute, read or write it. However, others can only execute or read the directory and its contents.

We may make the same directory in another way, as shown below.

- name: directory demonstration
  Ansible.builtin.file:
    path: /src/newdirectory
    state: directory
    mode: 0775

Check If the Directory Exists In Ansible

Checking whether a particular directory exists on Ansible follows the same procedure as checking for a file. The only difference is that we use the value isdir to confirm the directory’s path.

- name: check if directory exists already
  Debug:
    msg: “The directory exists”
    when: register_directory.stst.exists and register_directory.stat.isdir

Create a Directory With a Specific Path

- hosts: all
   tasks:
         - name: directory with specific path
        file:
          path: /home/folder1/my_new_directory
          state: directory

The script above makes a new directory in the subfolder “folder1” of the home directory. The directory is made under the file module, which handles the files, directories, and operations discussed above.

Change Permissions of a Directory

We may change the permissions on who can read, write, or execute the contents of a directory or file on the remote host using Ansible. The script is given below.

- hosts: all
  tasks:
     - name: directory permissions
       file:
                  path: /home/folder1/my_new_directory
                      state: directory
                      mode: "u=rw,g=wx,o=rwx"

Here we see that we changed permission (mode) to “u=rw,g=wx,o=rwx” This is a symbolic expression that tells the computer to let everyone read and write in the directory. The mode may be a symbolic expression or an octal number like “0755”.

Ambiguous Directory

In case we are not sure whether a directory already exists or not on our system, we may write a script that ensures that the directory will be checked if it exists. If it does not, a new directory by that name will be made on the remote host.

- hosts: localhost
   tasks:
      - name: Check directory if exist
        stat:
        path: /home/dir1
        register: newfolder

       - name: "in case directory existed"
         debug:
         msg: "given directory exists"
         when: newfolder.stat.exists

        - name: "Ansible Create directory if not exists"
          file:
             path: /home/dir1
             state: directory
             mode: 0755
             group: root
             owner: root
             when: new.stat.exists == false

Here the group and root show that access is allowed for the “root” owner and group

Conclusion

In this article, we learned about the stat and file modules in Ansible and how they help manage directories and files. We also went over Ansible scripts in case we wanted to make a directory that does not already exist. We hope you were able to find a solution to your confusion regarding directories in Ansible after reading this article.

About the author

Zeeman Memon

Hi there! I'm a Software Engineer who loves to write about tech. You can reach out to me on LinkedIn.