{"id":6073,"date":"2025-02-05T04:18:00","date_gmt":"2025-02-05T04:18:00","guid":{"rendered":"https:\/\/linuxbuz.com\/?p=6073"},"modified":"2025-07-11T04:43:36","modified_gmt":"2025-07-11T04:43:36","slug":"ansible-delegate_to-examples","status":"publish","type":"post","link":"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples","title":{"rendered":"How to Use Ansible delegate_to to Run Task on Specific Host"},"content":{"rendered":"<p style=\"text-align: justify;\">In Ansible, tasks usually run on the hosts listed in the inventory file. However, there are times when you need to execute a task on a different host. <a href=\"https:\/\/docs.ansible.com\/ansible\/latest\/playbook_guide\/playbooks_delegation.html\" target=\"_blank\" rel=\"noopener\"><strong>Ansible&#8217;s delegate_to module<\/strong><\/a> allows you to delegate a task from one host to another. This feature is handy for tasks involving centralized services or managing dependencies across multiple hosts.<\/p>\n<p style=\"text-align: justify;\"><em>In this guide, we&#8217;ll explain how to use the Ansible delegate_to module to run tasks on a specific host.<\/em><\/p>\n<div class=\"su-box su-box-style-default\" id=\"\" style=\"border-color:#001a66;border-radius:3px;max-width:none\"><div class=\"su-box-title\" style=\"background-color:#004d99;color:#FFFFFF;border-top-left-radius:1px;border-top-right-radius:1px\">\ud83d\udca1 Recommended Reading<\/div><div class=\"su-box-content su-u-clearfix su-u-trim\" style=\"border-bottom-left-radius:1px;border-bottom-right-radius:1px\">\n\ud83d\udc49 <a href=\"https:\/\/linuxbuz.com\/linuxhowto\/how-to-get-free-cloud-vps-server-step-by-step-guide\" target=\"_blank\" rel=\"noopener\">How to Get a Free Cloud Server for Testing<\/a><br \/>\n<\/div><\/div>\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#Basic_Syntax_and_Usage\" >Basic Syntax and Usage<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#Gathering_Facts_from_Different_Hosts\" >Gathering Facts from Different Hosts<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#Managing_Certificates_on_a_Central_Host\" >Managing Certificates on a Central Host<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#Running_Commands_on_Multiple_Hosts_Sequentially\" >Running Commands on Multiple Hosts Sequentially<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#Backing_Up_MySQL_Database\" >Backing Up MySQL Database<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#Running_Security_Scans_from_a_Security_Node\" >Running Security Scans from a Security Node<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/linuxbuz.com\/devops\/ansible-delegate_to-examples\/#FAQs\" >FAQs<\/a><\/li><\/ul><\/nav><\/div>\n\n<h2><span class=\"ez-toc-section\" id=\"Basic_Syntax_and_Usage\"><\/span>Basic Syntax and Usage<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">The basic syntax for using <strong>delegate_to<\/strong> is simple. You add the <strong>delegate_to<\/strong> keyword to a task and specify the target host. Here&#8217;s the basic syntax for using delegate_to in an Ansible playbook.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: Example playbook\r\n  hosts: target_host\r\n  tasks:\r\n    - name: Task to be executed on the target host\r\n      command: echo \"This is run on the target host\"\r\n      \r\n    - name: Task to be executed on a different host\r\n      command: echo \"This is run on the delegated host\"\r\n      delegate_to: delegated_host<\/code><\/pre>\n<p>In this example.<\/p>\n<ul>\n<li>First task runs on the <strong>target_host.<\/strong><\/li>\n<li style=\"text-align: justify;\">Second task is run on the delegated_host because of the <strong>delegate_to<\/strong> directive.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Gathering_Facts_from_Different_Hosts\"><\/span>Gathering Facts from Different Hosts<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">In some scenarios, you may need to gather facts from one host and use them on another. This example demonstrates <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-facts-example\" target=\"_blank\" rel=\"noopener\"><strong>how to gather facts<\/strong><\/a> from a <strong>database_server<\/strong> and use them on the <strong>web_server.<\/strong><\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>---\r\n- name: Gather facts from a different host\r\n  hosts: web_server\r\n  tasks:\r\n    - name: Gather facts from database server\r\n      ansible.builtin.setup:\r\n      delegate_to: database_server\r\n      register: db_facts\r\n\r\n    - name: Use database server facts on web server\r\n      ansible.builtin.debug:\r\n        msg: \"Database server IP is {{ db_facts.ansible_facts.ansible_default_ipv4.address }}\"<\/code><\/pre>\n<p style=\"text-align: justify;\">This playbook gathers facts from a <strong>database_server,<\/strong> stores them in <strong>db_facts,<\/strong> and then uses these facts to display the database server&#8217;s IP address on a <strong>web_server.<\/strong><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Managing_Certificates_on_a_Central_Host\"><\/span>Managing Certificates on a Central Host<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">Imagine you have a central server that manages SSL certificates for your web servers. You can use <strong>delegate_to<\/strong> to perform actions on this central server.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>---\r\n- name: Managing SSL certificates using delegate_to\r\n  hosts: web_server\r\n  tasks:\r\n    - name: Generate SSL certificate on central server\r\n      ansible.builtin.command: &gt;\r\n        openssl req -new -newkey rsa:2048 -nodes -keyout \/etc\/ssl\/private\/mycert.key -out \/etc\/ssl\/certs\/mycert.csr\r\n      delegate_to: central_cert_server\r\n\r\n    - name: Copy SSL certificate to web server\r\n      ansible.builtin.copy:\r\n        src: \/etc\/ssl\/certs\/mycert.csr\r\n        dest: \/etc\/ssl\/certs\/mycert.csr\r\n      delegate_to: web_server<\/code><\/pre>\n<p style=\"text-align: justify;\">In this scenario, the SSL certificate is generated on the <strong>central_cert_server<\/strong> with the <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-command-module-examples\" target=\"_blank\" rel=\"noopener\"><strong>command module<\/strong><\/a> and then copied to the <strong>web_server.<\/strong><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Running_Commands_on_Multiple_Hosts_Sequentially\"><\/span>Running Commands on Multiple Hosts Sequentially<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">You might need to perform a series of tasks on different hosts in a sequence. Here\u2019s how you can achieve that.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>---\r\n- name: Running commands on multiple hosts sequentially\r\n  hosts: all\r\n  tasks:\r\n    - name: Run a script on the first server\r\n      ansible.builtin.command: \/tmp\/script.sh\r\n      delegate_to: server1\r\n\r\n    - name: Run a script on the second server\r\n      ansible.builtin.command: \/tmp\/script.sh\r\n      delegate_to: server2\r\n\r\n    - name: Run a script on the third server\r\n      ansible.builtin.command: \/tmp\/script.sh\r\n      delegate_to: server3<\/code><\/pre>\n<p>In this example, each task runs a script on a different server in the specified order.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Backing_Up_MySQL_Database\"><\/span>Backing Up MySQL Database<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">Imagine you have a production MySQL database server that&#8217;s essential to your company&#8217;s operations. To protect your data, you decide to back up the database regularly to a separate backup server. This way, the main database server&#8217;s performance remains unaffected by the backup process, and your backups are safely stored in a different location.<\/p>\n<p style=\"text-align: justify;\">Here is an example playbook that connect to the <strong>db-server,<\/strong> creates a backup of the database, and then transfers it to the <strong>backup-server.<\/strong><\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>---\r\n- name: Backup MySQL database and transfer to backup server\r\n  hosts: db_servers\r\n  become: yes\r\n  vars:\r\n    db_name: db_name\r\n    db_user: db_user\r\n    db_password: db_password\r\n    backup_dir: \/tmp\/db_backups\r\n    backup_file: \"{{ db_name }}_backup_{{ ansible_date_time.iso8601 }}.sql\"\r\n    remote_backup_dir: \/var\/backups\/mysql\r\n\r\n  tasks:\r\n    - name: Install MySQL client\r\n      apt:\r\n        name: mysql-client\r\n        state: present\r\n\r\n    - name: Create backup directory\r\n      file:\r\n        path: \"{{ backup_dir }}\"\r\n        state: directory\r\n        mode: '0755'\r\n\r\n    - name: Backup MySQL database\r\n      command: &gt;\r\n        mysqldump -u{{ db_user }} -p{{ db_password }} {{ db_name }} &gt; {{ backup_dir }}\/{{ backup_file }}\r\n      environment:\r\n        MYSQL_PWD: \"{{ db_password }}\"\r\n\r\n    - name: Ensure remote backup directory exists on backup server\r\n      delegate_to: backup_servers\r\n      file:\r\n        path: \"{{ remote_backup_dir }}\"\r\n        state: directory\r\n        mode: '0755'\r\n\r\n    - name: Transfer backup to backup server\r\n      delegate_to: backup_servers\r\n      copy:\r\n        src: \"{{ backup_dir }}\/{{ backup_file }}\"\r\n        dest: \"{{ remote_backup_dir }}\/\"\r\n\r\n    - name: Clean up local backup file\r\n      file:\r\n        path: \"{{ backup_dir }}\/{{ backup_file }}\"\r\n        state: absent<\/code><\/pre>\n<p style=\"text-align: justify;\">This playbook:<\/p>\n<ul>\n<li style=\"text-align: justify;\">Installs the MySQL client on the <strong>db-server,<\/strong> backup the specified database, and temporarily stores the backup in a local directory.<\/li>\n<li style=\"text-align: justify;\">Uses the <strong style=\"font-size: 1rem;\">delegate_to<\/strong><span style=\"font-size: 1rem;\"> directive to create the backup directory on the <\/span><strong style=\"font-size: 1rem;\">backup-server<\/strong><span style=\"font-size: 1rem;\"> and copies the backup file with <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-copy-module-examples\" target=\"_blank\" rel=\"noopener\"><strong>copy module<\/strong><\/a>.<\/span><\/li>\n<li style=\"text-align: justify;\">Finally, it deletes the local backup file on the <strong style=\"font-size: 1rem;\">db-server<\/strong><span style=\"font-size: 1rem;\"> to free up space.<\/span><\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Running_Security_Scans_from_a_Security_Node\"><\/span>Running Security Scans from a Security Node<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">Tasks like vulnerability scans are often conducted in security-sensitive environments from dedicated security nodes. These nodes have the necessary permissions, tools, and configurations for performing comprehensive security checks.<\/p>\n<p>Here is an <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-playbooks-examples\" target=\"_blank\" rel=\"noopener\"><strong>example playbook<\/strong><\/a> that performs security scans on <strong>security_node.<\/strong><\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: Security Scans Playbook\r\n  hosts: all\r\n  become: yes\r\n  tasks:\r\n    - name: Run security scan on all hosts\r\n      command: nmap -sS -T4 {{ inventory_hostname }}\r\n      delegate_to: security_node\r\n      register: scan_results\r\n\r\n    - name: Display security scan results\r\n      debug:\r\n        msg: \"Scan results for {{ inventory_hostname }}: {{ scan_results.stdout }}\"<\/code><\/pre>\n<p style=\"text-align: justify;\">The above playbook:<\/p>\n<ul>\n<li style=\"text-align: justify;\">Uses a command module to run an <strong>Nmap<\/strong> scan on each host in the inventory. The scan is executed from the <strong>security_node,<\/strong> ensuring that all network scans are centralized and controlled.<\/li>\n<li style=\"text-align: justify;\">It then uses the <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-debug-module-examples\" target=\"_blank\" rel=\"noopener\"><strong style=\"font-size: 1rem;\">debug module<\/strong><\/a><span style=\"font-size: 1rem;\"> to output the security scan results for each host, allowing administrators to review any detected vulnerabilities or issues.<\/span><\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">This article explored the Ansible <strong>delegate_to<\/strong> module, starting with the basic syntax and progressing through several advanced, real-world examples. By leveraging delegate_to, you can efficiently manage tasks across different hosts, optimize your playbooks, and easily handle complex configurations.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"FAQs\"><\/span>FAQs<span class=\"ez-toc-section-end\"><\/span><\/h2>\n        <section class=\"sc_fs_faq sc_card \">\n            <div>\n\t\t\t\t<h6>1. What happens to facts collected when using delegate_to?<\/h6>                <div>\n\t\t\t\t\t                    <p>\n\t\t\t\t\t\tWhen using delegate_to, facts collected are from the delegated host, not the original host. Be mindful of this if you need specific data for the target host.                    <\/p>\n                <\/div>\n            <\/div>\n        <\/section>\n\t\t        <section class=\"sc_fs_faq sc_card \">\n            <div>\n\t\t\t\t<h6>2. How is delegate_to different from delegate_facts?<\/h6>                <div>\n\t\t\t\t\t                    <p>\n\t\t\t\t\t\tdelegate_to is used to run tasks on a specific host, whereas delegate_facts is used to delegate the collection of facts from one host to another.                    <\/p>\n                <\/div>\n            <\/div>\n        <\/section>\n\t\t        <section class=\"sc_fs_faq sc_card \">\n            <div>\n\t\t\t\t<h6>3. Can delegate_to be used for gathering facts?<\/h6>                <div>\n\t\t\t\t\t                    <p>\n\t\t\t\t\t\tNo, delegate_to is not typically used for gathering facts. Instead, you can target specific hosts using the hosts keyword for fact gathering.                    <\/p>\n                <\/div>\n            <\/div>\n        <\/section>\n\t\t\n<script type=\"application\/ld+json\">\n    {\n\t\t\"@context\": \"https:\/\/schema.org\",\n\t\t\"@type\": \"FAQPage\",\n\t\t\"mainEntity\": [\n\t\t\t\t{\n\t\t\t\t\"@type\": \"Question\",\n\t\t\t\t\"name\": \"1. What happens to facts collected when using delegate_to?\",\n\t\t\t\t\"acceptedAnswer\": {\n\t\t\t\t\t\"@type\": \"Answer\",\n\t\t\t\t\t\"text\": \"When using delegate_to, facts collected are from the delegated host, not the original host. Be mindful of this if you need specific data for the target host.\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t}\n\t\t\t,\t\t\t\t{\n\t\t\t\t\"@type\": \"Question\",\n\t\t\t\t\"name\": \"2. How is delegate_to different from delegate_facts?\",\n\t\t\t\t\"acceptedAnswer\": {\n\t\t\t\t\t\"@type\": \"Answer\",\n\t\t\t\t\t\"text\": \"delegate_to is used to run tasks on a specific host, whereas delegate_facts is used to delegate the collection of facts from one host to another.\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t}\n\t\t\t,\t\t\t\t{\n\t\t\t\t\"@type\": \"Question\",\n\t\t\t\t\"name\": \"3. Can delegate_to be used for gathering facts?\",\n\t\t\t\t\"acceptedAnswer\": {\n\t\t\t\t\t\"@type\": \"Answer\",\n\t\t\t\t\t\"text\": \"No, delegate_to is not typically used for gathering facts. Instead, you can target specific hosts using the hosts keyword for fact gathering.\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t}\n\t\t\t\t    ]\n}\n<\/script>\n\n","protected":false},"excerpt":{"rendered":"<p>In Ansible, tasks usually run on the hosts listed in the inventory file. However, there are times when you need to execute a task on a different host. Ansible&#8217;s delegate_to &hellip; <\/p>\n","protected":false},"author":1,"featured_media":6074,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"two_page_speed":[],"footnotes":""},"categories":[828],"tags":[],"class_list":["post-6073","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-devops"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/posts\/6073","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/comments?post=6073"}],"version-history":[{"count":0,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/posts\/6073\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/media\/6074"}],"wp:attachment":[{"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/media?parent=6073"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/categories?post=6073"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/tags?post=6073"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}