Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Ansible run one certain task only on one host?

Tags:

ansible

The playbook looks like:

- hosts: all   tasks:     - name: "run on all hosts,1"       shell: something1     - name: "run on all hosts,2"       shell: something2     - name: "run on one host, any host would do"       shell: this_command_should_run_on_one_host     - name: "run on all hosts,3"       shell: something3 

I know with command line option --limit, I can limit to one host, is it possible to do it in playbook?

like image 736
nuster cache server Avatar asked Nov 17 '17 03:11

nuster cache server


People also ask

How do I make an Ansible task run only once?

For such requirements where we need one tasks to run only once on a batch of hosts and we will be running that from Ansible controller node, we have feature parameter named run_once. When we have this parameter mentioned in a task, that task will run only once on first host it finds despite the host batch.

How do I run a specific task in Ansible playbook?

The easiest way to run only one task in Ansible Playbook is using the tags statement parameter of the “ansible-playbook” command. The default behavior is to execute all the tags in your Playbook with --tags all .

How do I limit Ansible hosts?

You can also limit the hosts you target on a particular run with the --limit flag. Negated limit. Note that single quotes MUST be used to prevent bash interpolation.

Which option would target a playbook to run only on certain hosts?

Ansible command limit option Using the --limit parameter of the ansible-playbook command is the easiest option to limit the execution of the code to only one host. The advantage is that you don't need to edit the Ansible Playbook code before executing to only one host.


Video Answer


1 Answers

For any host (with defaults it will match the first on the list):

- name: "run on first found host"   shell: this_command_should_run_on_one_host   run_once: true 

For a specific host:

- name: "run on that_one_host host"   shell: this_command_should_run_on_one_host   when: ansible_hostname == 'that_one_host' 

Or inventory_hostname (hostname as defined in the Ansible inventory) instead of ansible_hostname (hostname as defined on the target machine), depending on which name you want to use.

like image 185
techraf Avatar answered Oct 07 '22 08:10

techraf