# choose random host frm the playbook to delegate to

**URL:** <https://forum.ansible.com/t/choose-random-host-frm-the-playbook-to-delegate-to/25542>\
**Category:** Ansible Project\
**Created:** [September 20, 2017, 7:45am UTC](https://forum.ansible.com/t/choose-random-host-frm-the-playbook-to-delegate-to/25542 "2017-09-20T07:45:56Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hudec\_Peter](https://avatars.discourse-cdn.com/v4/letter/h/a87d85/32.png) [@Hudec\_Peter](https://forum.ansible.com/u/Hudec_Peter)\
**Post date:** [September 20, 2017, 7:45am UTC](https://forum.ansible.com/t/choose-random-host-frm-the-playbook-to-delegate-to/25542/1 "2017-09-20T07:45:56Z")

</div>

Hi,  
I need to run jib on one host from the hosts in playbook. To distribute  
it, should be random host. But as many time as I run the playbook,  
always the first host is chosen. Please, what do I wrong? Right now ,  
there are only two hosts in the list. See sample playbook.

ansible 2.2.1.0

- hosts: jobs  
&nbsp;&nbsp;vars:  
&nbsp;&nbsp;&nbsp;&nbsp;lock\_file: /tmp/test.lock

&nbsp;&nbsp;pre\_tasks:  
&nbsp;&nbsp;- name: "create lock file"  
&nbsp;&nbsp;&nbsp;&nbsp;file:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;path: "{{ lock\_file }}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mode: 0600  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;owner: root  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;group: root  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;state: touch

&nbsp;&nbsp;tasks:  
&nbsp;&nbsp;- set\_fact:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;job\_host: "{{ ansible\_play\_batch|random }}"  
&nbsp;&nbsp;&nbsp;&nbsp;run\_once: True  
&nbsp;&nbsp;&nbsp;&nbsp;delegate\_to: '127.0.0.1'

&nbsp;&nbsp;- name: "do action on one host"  
&nbsp;&nbsp;&nbsp;&nbsp;file:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;path: "{{ lock\_file }}.xxx"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mode: 0600  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;owner: root  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;group: root  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;state: touch  
&nbsp;&nbsp;&nbsp;&nbsp;run\_once: True  
&nbsp;&nbsp;&nbsp;&nbsp;delegate\_to: "{{ job\_host }}"

&nbsp;&nbsp;post\_tasks:  
&nbsp;&nbsp;- name: "remove lock file"  
&nbsp;&nbsp;&nbsp;&nbsp;file:  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;path: "{{ lock\_file }}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;state: absent

&nbsp;&nbsp;thanks  
&nbsp;&nbsp;&nbsp;&nbsp;Peter
