Ansible is installed and you are eager to write your first playbook. We have to setup a basic inventory file and create the playbook. Log into your Ansible controller via SSH and let’s get started.
Create Playbook directory
[root@ansible ~]# mkdir playbook
[root@ansible ~]# cd playbook
[root@ansible playbook]#
Next we are going to create a basic inventory file. We are going to use INI style inventory file. You can also create a YAML style file as well.
Create Inventory file
INI style
[root@ansible playbook]# touch hosts.ini
[root@ansible playbook]# vi hosts.ini
hosts.ini
127.0.0.1
YAML style
[root@ansible playbook]# touch hosts.yml
[root@ansible playbook]# vi hosts.yml
hosts.yml
all:
hosts:
127.0.0.1
This inventory file will connect to the localhost machine that you are running Ansible from. If you have a test linux server, you can add it instead of ‘127.0.0.1’.
Create playbook file
The playbook file is written in YAML syntax. This will be the main file that includes task that can run using Ansible. We are going to be using the ping module in this playbook. It will basically verify a usable python and return pong if successful.
[root@ansible playbook]# touch main.yml
[root@ansible playbook]# vi main.yml
main.yml
---
- hosts: all
name: First playbook
tasks:
- name: Ping module
ping:
Running your playbook
Now it is time to run your first playbook. If you are using password authentication with SSH, you may have to install sshpass package based on your package manager. You will be asked for the root user password after executing the following commands.
INI style inventory
[root@ansible playbook]# ansible-playbook -i hosts.ini -u root -k main.yml
SSH password:
YAML style inventory
[root@ansible playbook]# ansible-playbook -i hosts.yml -u root -k main.yml
SSH password:
Results
If everything was successful, you will see the following output. It is verifying a workable python package and responding with pong.
PLAY [First playbook] **********************************************************
TASK [Gathering Facts] *********************************************************
ok: [127.0.0.1]
TASK [Ping host] ***************************************************************
ok: [127.0.0.1]
PLAY RECAP *********************************************************************
127.0.0.1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Conclusion
That is the basics to writing a basic playbook and inventory file. This is the first building block on creating more complex playbooks. Keep an eye out for more complex examples to get you started.