Saturday 26 May 2018

Ansible delegate_to

In this post, we will see the use of Ansible delegation using delegate_to


Purpose:

By default, on remote configure machine, Ansible run the task all at once. Consider the situation where task is based on status / output of a certain command on another machine. For example, if we are doing patching a package on a machine and you need to continue until a certain file is available on another machine. This can be achieved in Ansible using the delegation option.

As the terminology indicates, through Ansible delegate option we can configure to run a task on a different host (and not the default one) than the one that is being configured using the delegate_to key. The module will still run once for every machine, but instead of running on the target machine, it will run on the delegated host. The facts available will be the ones applicable to the current host. 


Code Example / Playbook using Ansible delegate:

[root@server1 delegate]# cat delegation-playbook.yml
---
- hosts: cent
 
  tasks:
    - name: Install zenity
      action: yum name=zenity state=installed
    - name: configure zenity
      action: template src=hosts dest=/tmp/zenity.conf
    - name: Tell Master
      action: shell echo "{{ansible_fqdn}} done" >> /tmp/list
      delegate_to: 172.16.202.99

We have defined multiple tasks to install zenity, configure zenity and the last task is to echo command on the delegate machineof different IP address.  Ansible-playbook will delegate the last task to the IP address 172.16.202.99. 

Once we run the playbook we can see the following:

[root@server1 delegate]# ansible-playbook delegation-playbook.yml

PLAY [cent] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.16.202.96]

TASK: [Install zenity] ********************************************************
changed: [172.16.202.96]

TASK: [configure zenity] ******************************************************
changed: [172.16.202.96]

TASK: [Tell Master] ***********************************************************
changed: [172.16.202.96 -> 172.16.202.99]

PLAY RECAP ********************************************************************
172.16.202.96              : ok=4    changed=3    unreachable=0    failed=0  

Now we can check the remote machine 172.16.202.99 for the file created.

root@ubuntu:/home/vagrant# cat /tmp/list
dev.foohost.vm done

Thats all for usage of Ansible delegation using delegate_to.