How to write Ansible Playbook

We’ve already seen Introduction to Ansible, Ansible Architecture and Installation. Now we will be seeing What is Ansible Playbook and how do we write one.

So let’s get started.

As per Redhat An Ansible® playbook is a blueprint of automation tasks—which are complex IT actions executed with limited or no human involvement. Ansible playbooks are executed on a set, group, or classification of hosts, which together make up an Ansible inventory.

Playbooks can:

  • declare configurations
  • orchestrate steps of any manual ordered process, on multiple sets of machines, in a defined order
  • launch tasks synchronously or asynchronously

Let us take a scenario to install Git on a remote machine. When we do it manually the steps involved are

sudo apt-get update 
sudo apt-get install git -y

Now let’s try to write the same using Ansible Playbook, create a file sample-playbook.yml

- hosts: all 
  become: yes 
    - name: update ubuntu packages and install git
        name: git
        update_cache: yes 
        state: present

Now our Playbook is ready, let’s create a new file called hosts_inventory and write all the inventories.

 vi hosts_inventory
 # write the private ip address of the machine you want playbook to be executed on it.

Now Command to execute to run this playbook.

ansible-playbook -i hosts_inventory  sample-playbook.yml 

Now wait for the magic to happen! Login to the machine where you wanted git to be installed and check.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s