Saturday, 26 May 2018

Ansible delegate_to

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


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
    - 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

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 

Once we run the playbook we can see the following:

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

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

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

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

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

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

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

Now we can check the remote machine 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.

No comments:

Post a comment