How to create a directory and a file using ansible-playbook on Ubuntu 21.04

66
0

Prerequisites

Before getting started, you will need to have access to a server running Ubuntu 21.04 and have root access to that server. You will also need to install the Ansible package.

Installing Ansible

In order to install Ansible, you will need to add the PPA repository for Ansible to your sources list. This can be done by running the following command:

sudo add-apt-repository ppa:ansible/ansible

Once the repository has been added, you will need to update your sources list with the command:

sudo apt-get update

Finally, you can install Ansible with the command:

sudo apt-get install ansible

Setting Up the Playbook

An Ansible playbook is the file responsible for defining the tasks that Ansible will execute on the remote server. In this example, we will create a playbook that will create a directory and a file in the root of the server.

To create the playbook, you will need to open up a text editor and create a file called ā€œplaybook.ymlā€. In this file, we will need to define the tasks that we want Ansible to execute.

Creating a Directory

The first task that we will define is to create a directory. To do this, we will use the Ansible ā€œfileā€ module. This module allows us to create, delete and manage files and directories.

We will use the ā€œfileā€ module to create a directory called ā€œmydirā€ in the root directory of the server. To do this, we will need to add the following code to the playbook:

- name: Create Directory
file:
path: /mydir
state: directory

This will tell Ansible to create a directory called ā€œmydirā€ in the root of the server.

Creating a File

The next task that we will define is to create a file. To do this, we will use the same ā€œfileā€ module that we used to create the directory.

We will create a file called ā€œmyfile.txtā€ in the root directory of the server. To do this, we will need to add the following code to the playbook:

- name: Create File
file:
path: /myfile.txt
state: touch

This will tell Ansible to create a file called ā€œmyfile.txtā€ in the root of the server.

Running the Playbook

Once the playbook is ready, you can run it with the following command:

ansible-playbook playbook.yml

This will execute the tasks defined in the playbook, creating the directory and the file in the root of the server.

Conclusion

In this tutorial, we have seen how to use Ansible to create a directory and a file on a server running Ubuntu 21.04. We have seen how to install Ansible, how to set up the playbook and how to run it. We hope you have found this tutorial useful

Previous articleļ‚· OS drive
Next articleHow to earn from chat GPT