MFH LABS : First Ansible Playbook

Step 01 —

First, create a project folder and add the configuration files for the playbook.

mkdir ansible/cd ansible

Then create a new configuration file host and site.yml.

touch hosts site.yml

Now create a new directory called roles.

mkdir roles/

Step 02 —

Second, generate Ansible roles for the directory structure. For this task we are using a role named myuser. Redirect to the /roles folder.

cd roles/

Now execute the following command to generate the folder structure.

ansible-galaxy init myuseroutput: WARNING: Executing a script that is loading libcrypto in an unsafe way. This will fail in a future version of macOS. Set the LIBRESSL_REDIRECT_STUB_ABORT=1 in the environment to force this into an error.
- Role myuser was created successfully

You will find the following folder structure in your project folder

tree .
├── hosts
├── roles
│ └── myuser
│ ├──
│ ├── defaults
│ │ └── main.yml
│ ├── files
│ ├── handlers
│ │ └── main.yml
│ ├── meta
│ │ └── main.yml
│ ├── tasks
│ │ └── main.yml
│ ├── templates
│ ├── tests
│ │ ├── inventory
│ │ └── test.yml
│ └── vars
│ └── main.yml
└── site.yml10 directories, 10 files

Let me talk you on a quick walkthrough around the files we created up to now.

  1. site.yaml — This is the playbook file. This contains the group of hosts that will be managed using the available roles.
  2. hosts — It is an inventory file which contains the details of the managed nodes (IP addresses)
  3. roles — A group of Ansible playbooks used to provision the managed nodes.

Step 03 —

The third part is to set up the hosts and the site.yml file. Open the hosts file and paste the following part. Then save and exit.


Same, open site.yml file, paste the following part, save and exit.

- name: “Play 1”
hosts: localhost
— myuser

Step 04 —

Part 04 is to set up the roles. In our case let’s setup myuser role. Open main.ymlin /roles/myuser/tasks. This file is to define the tasks related to the role. The tasks are defined in several methods. For this task, we will make the role to create a folder. Paste the following code to the main.yml and save.

- name: Task 01
command: mkdir task01/

The tasks can be named as you want with the name: tag.

Step 05 —

The final step is to run the playbook.

ansible-playbook site.yml

If you check your directory structure you will find out the new folder task01.

So, this is all for writing a simple Ansible playbook. Let us get back with a more complex as multiple hosts in next article.