Tag Archives: playbook

Ansible: From install to roles in 5 minutes

Here’s a real quick walkthrough from install of Ansible to a primitive role based playbook.

Install ansible and create/edit our ansible hosts file:-

steve@devbox:~$ sudo aptitude install ansible
steve@devbox:~$ sudo vi /etc/ansible/hosts


In my case I have a single target in the ‘test’ group:-

I copy my private key to the remote system (authorized_keys) ensuring permissions are correct.
We should then be able to do an ansible ping. Be aware you will need python installed on the target.

steve@devbox:~$ ansible -m ping all | SUCCESS => {
    "changed": false, 
    "ping": "pong"

Now I make a basic directory structure to store our yaml files.

steve@devbox:~$ mkdir ansible/roles
steve@devbox:~$ cd ansible/roles

ansible-galaxy can help us with the layout of the role directory structure:-

steve@devbox:~$ ansible-galaxy init time
- time was created successfully

Let’s take a look at what ansible-galaxy has created for us:-

steve@devbox:~$ cd time; ls
defaults  files  handlers  meta  README.md  tasks  templates  tests  vars

Great stuff. Let’s start by creating a task. I’d like to install NTP and ensure it’s running.

steve@devbox:~$ cd tasks
steve@devbox:~$ vi main.yml

# tasks file for time
- name: Install NTP
  apt: pkg=ntp state=installed update_cache=true
  notify: start ntp

The above includes a ‘notify’ for a handler to take action. Let’s create that handler:-

steve@devbox:~$ cd ../handlers
steve@devbox:~$ vi main.yml

# handlers file for time
- name: start ntp
  service: name=ntp state=started

Now move back to the root of our ansible configs and create a simple playbook (site.yml)

steve@devbox:~$ cd ~/ansible
steve@devbox:~$ vi site.yml


- name: test ntp via time role
  hosts: all
  become: true

    - time

The above indicates we want all hosts to include the NTP role. We’ll need to ‘become root’ on the target in order to install software. The role we want to run is called ‘time’ (as per the ansible-galaxy init and our resultant direcctory structure).

Finally, let’s run the site playbook:-

steve@devbox:~$ ansible-playbook site.yaml

PLAY [test ntp via time role] **************************************************

TASK [setup] *******************************************************************
ok: []

TASK [time : Install NTP] ******************************************************
changed: []

RUNNING HANDLER [time : start ntp] *********************************************
ok: []

PLAY RECAP *********************************************************************                  : ok=3    changed=1    unreachable=0    failed=0