How to run a task from a playbook to a specific host
-
I'm writing an ansible playbook to manage backup and I want two different tasks :
- name: Setup local machine for backup cron: cron_file: /etc/cron.d/backup hour: 4 minute: 0 job: /root/do_backup.sh state: present name: backup
- name: Setup backup server for new machine
shell:
cmd: "mkdir /backups/{{inventory_hostname}}"
Is it possible to tell ansible that second task is intended to be executed on another machine of my inventory ?
I don't want a dedicated playbook, because some later tasks should be executed after the task on backup server.
- name: Setup backup server for new machine
-
This is a duplicate of this StackOverflow https://stackoverflow.com/questions/31912748/how-to-run-a-particular-task-on-specific-host-in-ansible .
But I will combine and summarize all the answers here.
If your "other_host" is in the playbooks inventory then you can use the https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html keyword:
when: inventory_hostname is "other_host"
. Which will only run that task once and only for "other_host".If your playbook inventory does not include "other_host" then you can use the https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html keyword.
delegate_to: other_host_ip
. Not that you have to use the IP or DNS name of the machine unless you use https://docs.ansible.com/ansible/latest/collections/ansible/builtin/add_host_module.html#add-host-module module. This will run the task for EVERY host in the playbooks inventory but will run the tasks onother_host
.