Ansible

How to Create a Directory in Ansible

Ansible is one of the best automation tools available, offering simple, intuitive, and powerful tools to perform automation tasks in the modern world.

For most automation tasks, you will need to create directories, especially when installing various tools and applications, backups, and restores. Though you can perform these tasks using an automated script, Ansible provides better functionality, allowing you to create directories in specified hosts.

This tutorial shows you how to use the Ansible file module to create, remove, and modify directory permissions for specified hosts.

How to Create a Directory in Ansible

Either of the following methods can be used to create a directory in Ansible:

  • A raw Ansible command with the command module
  • A file module in an Ansible playbook

To create a directory in Ansible using the command module, enter the command shown below:

$ ansible all -m command -a "mkdir ~/backups"

After inputting the above command, you should obtain the output shown below:

Enter passphrase for key '/home/user/.ssh/id_rsa':
[WARNING]: Consider using the file module with state=directory rather than running 'mkdir'.  If you need to use command because file is insufficient you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
35.222.210.12 | CHANGED | rc=0 >>

Verify that your Ansible hosts inventory in /etc/ansible/hosts contains the correct information about your remote hosts.

Though the command module is simple to use on a single Ansible host, it becomes very inefficient when dealing with multiple hosts with different directories and tasks.

To counter this drawback, we will use the Ansible file module and build a playbook containing the hosts that we want to use and the directories that we wish to create.

NOTE: The file module can also be used as a single command in Ansible, but it works much like the command module.

To use an Ansible playbook, create a YAML file and enter the following entries to create a directory:

- hosts: all   tasks:
 - name: Ansible file module create directory    

    file:
     path: ~/backups      

      state: directory

Save the file and use ansible-playbook to create the directories:

ansible-playbook mkdir.yml

This should produce an output like the one below, indicating that the actions were carried out successfully using the specified playbook file.

PLAY [all] *************************************************************************************************************
TASK [Gathering Facts] *************************************************************************************************
Enter passphrase for key '/home/user/.ssh/id_rsa':
ok: [35.222.210.12]
  TASK [Ansible file module create directory] ****************************************************************************
ok: [35.222.210.12]
  PLAY RECAP *************************************************************************************************************
35.222.210.12              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

How to Create Multiple Directories with Items

Ansible playbooks also allow you to create multiple directories using the with_items statement in the YAML file.

For example, to create backups for the three services, MySQL, repository, and config, you can build the task shown in the YAML file below:

- hosts: all   tasks:
 - name: Ansible create multiple directories with_items    

    file:
     path: ~/backups/{{item}}
     state: directory    

      with_items:
         - 'mysql'      

          - 'repository'      

          - 'config'

Save the above file and run it with ansible-playbook.

$ ansible-playbook mkdir_multi.yml   PLAY [all] ******************************************************************************************************************************************************************************************************
  TASK [Gathering Facts] ******************************************************************************************************************************************************************************************
Enter passphrase for key '/home/user/.ssh/id_rsa':
ok: [35.222.210.12]
  TASK [Ansible create multiple directories with_items] ***********************************************************************************************************************************************************
changed: [35.222.210.12] => (item=mysql)
changed: [35.222.210.12] => (item=repository)
changed: [35.222.210.12] => (item=config)
  PLAY RECAP ******************************************************************************************************************************************************************************************************
35.222.210.12              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The above playbook should create multiple directories, such as ~/backups/mysql, ~/backups/repository, and ~/backups/config.

$ ls -la

The directory list output is as shown below:

total 0

drwxrwxr-x. 5 debian debian  51 Mar  6 17:26 .
drwx------. 6 debian debian 117 Mar  6 17:26 ..
drwxrwxr-x. 2 debian debian   6 Mar  6 17:26 config

drwxrwxr-x. 2 debian debian   6 Mar  6 17:26 mysql

drwxrwxr-x. 2 debian debian   6 Mar  6 17:26 repository

How to Set Permissions for a Directory

Ansible allows you to specify permissions for a directory using the mode directive. Consider the following playbook, which creates a directory and sets permissions:

- hosts: all  

  tasks:

   - name: Ansible create directory and set permissions    

     file:
       path: /backups      

        state: directory      

        mode: "u=rw,g=wx,o=rwx"    

   become: yes

In the above entry, we created a directory in /. We also needed to become root, hence the become: yes entry.

$ ansible-playbook permission.yml   PLAY [all] ******************************************************************************************************************************************************************************************************
  TASK [Gathering Facts] ******************************************************************************************************************************************************************************************
Enter passphrase for key '/home/user/.ssh/id_rsa':
ok: [35.222.210.12]
  TASK [Ansible create directory and set permissions] *************************************************************************************************************************************************************
changed: [35.222.210.12]
  PLAY RECAP ******************************************************************************************************************************************************************************************************
35.222.210.12              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

If you view the permissions of the directory we created, you will see the following:

$ ls -lrt / | grep backups

The output is as shown below:

drw--wxrwx.   2 root root    6 Mar  6 17:36 backups

How to Recursively Change Permissions in a Directory

To change the permissions of a directory and its files recursively, simply specify the recursive entry, as shown below:

- hosts: all  

  tasks:
 - name: Ansible create directory and set permissions    

    file:
     path: /backups      

      state: directory      

      mode: "u=rw,g=wx,o=rwx"      

      recursive: yes    

  become: yes

How to Set Permissions in Multiple Directories

Setting up permissions for multiple directories in Ansible is also as simple as a few lines of entries. Consider the following playbook.

- hosts: all  

  tasks:
 - name: Ansible create mutliple directory with permissions  

    file:
     path: "{{ item.path }}"      

      mode: "{{item.mode}}"      

      state: directory    

      with_items:
        - { path: '~/backups/mysql', mode: '0777'}
        - { path: '~/backups/repository', mode: '0755'}
        - { path: '~/backups/config', mode: '0707'}

How to Delete a Directory in Ansible

To remove a directory and all its contents using an Ansible playbook, specify the state as absent, as shown below:

- hosts: all  

  tasks:
 - name: Ansible delete directory    

    file:
     path: /backups      

      state: absent    

  become: yes

This command will remove the directory and all the children files and directories.

NOTE: Make sure that you have permissions for the directory that you are working on.

How to Create a Timestamped Directory

In some cases, you may need to create a directory with a timestamp attached to it, which can be very useful, especially when creating backups. To create a timestamped directory, we can use the ansible_date_time variable.

Consider the following playbook:

- hosts: all  

  tasks:
 - name: Ansible add timestamp to directory    

    file:
     path: "/backups/mysql{{ansible_date_time.date}}"      

      state: directory      

      mode: "0777"    

  become: yes

Once you run the playbook, you will have a directory with the timestamp.

$ ls -l

The Directory Listing should be as shown below:

total 0 drwxrwxrwx. 2 root root 6 Mar  6 18:03 mysql2021-03-06

NOTE: To avoid errors, always check the YAML file syntax that you intend to use in Ansible.

Conclusion

This tutorial showed you that working with Ansible modules is very easy and intuitive, making automating complex tasks simpler. Using the Ansible file module, you can create one or more directories and add permissions for each. You can also use the same module to remove a directory For more information on how to use the Ansible file module, check the official documentation at the resource page.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list