{"id":5707,"date":"2025-01-09T10:03:09","date_gmt":"2025-01-09T10:03:09","guid":{"rendered":"https:\/\/linuxbuz.com\/?p=5707"},"modified":"2025-07-11T04:54:54","modified_gmt":"2025-07-11T04:54:54","slug":"ansible-command-module-examples","status":"publish","type":"post","link":"https:\/\/linuxbuz.com\/devops\/ansible-command-module-examples","title":{"rendered":"Ansible Command Module Explained with Examples"},"content":{"rendered":"<p style=\"text-align: justify;\">The <a href=\"https:\/\/docs.ansible.com\/ansible\/latest\/collections\/ansible\/builtin\/command_module.html\" target=\"_blank\" rel=\"noopener\"><strong>command module<\/strong><\/a> in Ansible runs commands on a target host. Unlike the <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-shell-module\" target=\"_blank\" rel=\"noopener\"><strong>shell module<\/strong><\/a>, it executes the command directly without invoking a shell. This ensures a higher level of security because shell features like redirection, piping, or variable substitution are not supported.<\/p>\n<p><strong>Key Features:<\/strong><\/p>\n<ul>\n<li>Runs command in a non-interactive manner.<\/li>\n<li>Does not process shell operators like |, &amp;&amp;, or $.<\/li>\n<li style=\"text-align: justify;\">Can be used for tasks like checking system status, starting\/stopping services, or managing simple configurations.<\/li>\n<\/ul>\n<p style=\"text-align: justify;\"><em>In this article, we\u2019ll explore the <strong>Ansible command module<\/strong> with practical examples.<\/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-command-module-examples\/#Basic_Syntax\" >Basic Syntax<\/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-command-module-examples\/#Example_1_Basic_Execution\" >Example 1: Basic Execution<\/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-command-module-examples\/#Example_2_Using_Arguments_in_Commands\" >Example 2: Using Arguments in Commands<\/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-command-module-examples\/#Example_3_Creating_Files_Conditionally\" >Example 3: Creating Files Conditionally<\/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-command-module-examples\/#Example_4_Changing_Directories_Before_Execution\" >Example 4: Changing Directories Before Execution<\/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-command-module-examples\/#Example_5_Combining_Command_with_Loops\" >Example 5: Combining Command with Loops<\/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-command-module-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-command-module-examples\/#FAQs\" >FAQs<\/a><\/li><\/ul><\/nav><\/div>\n\n<h2><span class=\"ez-toc-section\" id=\"Basic_Syntax\"><\/span>Basic Syntax<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Here is the basic syntax:<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: Task description\r\n  hosts: target_host\r\n  tasks:\r\n    - name: Execute a command\r\n      ansible.builtin.command:\r\n        cmd: command-name<\/code><\/pre>\n<p><strong>Explanation:<\/strong><\/p>\n<ul>\n<li style=\"text-align: justify;\"><strong>cmd:<\/strong> The command to be executed.<\/li>\n<li style=\"text-align: justify;\"><strong>chdir:<\/strong> Changes the working directory before running the command.<\/li>\n<li style=\"text-align: justify;\"><strong>creates:<\/strong> Specifies a file path; if the file exists, the command will not run.<\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Example_1_Basic_Execution\"><\/span>Example 1: Basic Execution<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">This playbook run the <strong>uptime<\/strong> command to check the system&#8217;s uptime on the target host and displays the output with the <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-debug-module-examples\" target=\"_blank\" rel=\"noopener\"><strong>debug<\/strong> <strong>module<\/strong><\/a>.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: Check system uptime\r\n  hosts: all\r\n  tasks:\r\n    - name: Run uptime command\r\n      ansible.builtin.command:\r\n        cmd: uptime\r\n      register: uptime_result\r\n\r\n    - name: Display uptime output\r\n      debug:\r\n        msg: \"System uptime: {{ uptime_result.stdout }}\"<\/code><\/pre>\n<h2><span class=\"ez-toc-section\" id=\"Example_2_Using_Arguments_in_Commands\"><\/span>Example 2: Using Arguments in Commands<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">Run a command with additional arguments, such as listing detailed file information.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: List files in a directory\r\n  hosts: all\r\n  tasks:\r\n    - name: List files in \/etc\r\n      ansible.builtin.command:\r\n        cmd: ls -l \/etc\r\n      register: list_files_result\r\n\r\n    - name: Display file list\r\n      debug:\r\n        msg: \"Files in \/etc:\\n{{ list_files_result.stdout }}\"<\/code><\/pre>\n<p>This <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-playbooks-examples\" target=\"_blank\" rel=\"noopener\"><strong>playbook<\/strong><\/a> lists all files and directories in <strong>\/etc<\/strong> in a detailed format.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Example_3_Creating_Files_Conditionally\"><\/span>Example 3: Creating Files Conditionally<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p style=\"text-align: justify;\">Create a file only if it doesn\u2019t already exist, and confirm the action.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: Conditionally create a file\r\n  hosts: all\r\n  tasks:\r\n    - name: Create file if it doesn't exist\r\n      ansible.builtin.command:\r\n        cmd: touch \/tmp\/newfile.txt\r\n        creates: \/tmp\/newfile.txt\r\n      register: create_file_result\r\n\r\n    - name: Display file creation status\r\n      debug:\r\n        msg: \"File creation output: {{ create_file_result.stdout }}\"<\/code><\/pre>\n<p style=\"text-align: justify;\">Here, the creates parameter ensures the command runs only if the specified file does not exist.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Example_4_Changing_Directories_Before_Execution\"><\/span>Example 4: Changing Directories Before Execution<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Run a command in a specific directory.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: Run commands in a specific directory\r\n  hosts: all\r\n  tasks:\r\n    - name: List files in \/tmp\r\n      ansible.builtin.command:\r\n        cmd: ls -l\r\n        chdir: \/tmp\r\n      register: directory_list_result\r\n\r\n    - name: Display directory contents\r\n      debug:\r\n        msg: \"Directory contents:\\n{{ directory_list_result.stdout }}\"<\/code><\/pre>\n<p style=\"text-align: justify;\">In this playbook, the <strong>chdir<\/strong> args changes the current working directory to <strong>\/tmp<\/strong> before running the ls <strong>-l<\/strong> command.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Example_5_Combining_Command_with_Loops\"><\/span>Example 5: Combining Command with Loops<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Run the same command on <strong>multiple files<\/strong> using a <a href=\"https:\/\/linuxbuz.com\/devops\/ansible-loops-example\" target=\"_blank\" rel=\"noopener\"><strong>loop<\/strong><\/a>.<\/p>\n<pre style=\"background-color: #262626; color: white; border-radius: 7px; overflow: auto;\"><code>- name: Display file sizes\r\n  hosts: all\r\n  tasks:\r\n    - name: Check file sizes in \/tmp\r\n      ansible.builtin.command:\r\n        cmd: du -sh \/tmp\/{{ item }}\r\n      with_items:\r\n        - file1.txt\r\n        - file2.log\r\n        - dir1\r\n      register: file_sizes_result\r\n\r\n    - name: Display file size results\r\n      debug:\r\n        var: file_sizes_result.results | map(attribute='stdout') | join('\\n')<\/code><\/pre>\n<p style=\"text-align: justify;\">Here, the task calculates the size of multiple files and directories in <strong>\/tmp<\/strong> and displays the output.<\/p>\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;\">The <strong>Ansible command module<\/strong> is a powerful tool for executing simple commands on remote systems. While it doesn\u2019t provide the flexibility of the <strong>shell module,<\/strong> its security and simplicity make it an excellent choice for basic administrative tasks.<\/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. Can I run commands as a specific user?<\/h6>                <div>\n\t\t\t\t\t                    <p>\n\t\t\t\t\t\tYes, you can use the become directive in the playbook to run the command as a different user.                    <\/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. Does this Ansible Module support conditional execution?<\/h6>                <div>\n\t\t\t\t\t                    <p>\n\t\t\t\t\t\tYes, you can use Ansible conditionals like when to control when a command runs.                    <\/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 I capture the output of a command ?<\/h6>                <div>\n\t\t\t\t\t                    <p>\n\t\t\t\t\t\tYes, use the register keyword to store the output and access it using variables like result.stdout.                    <\/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. Can I run commands as a specific user?\",\n\t\t\t\t\"acceptedAnswer\": {\n\t\t\t\t\t\"@type\": \"Answer\",\n\t\t\t\t\t\"text\": \"Yes, you can use the become directive in the playbook to run the command as a different user.\"\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. Does this Ansible Module support conditional execution?\",\n\t\t\t\t\"acceptedAnswer\": {\n\t\t\t\t\t\"@type\": \"Answer\",\n\t\t\t\t\t\"text\": \"Yes, you can use Ansible conditionals like when to control when a command runs.\"\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 I capture the output of a command ?\",\n\t\t\t\t\"acceptedAnswer\": {\n\t\t\t\t\t\"@type\": \"Answer\",\n\t\t\t\t\t\"text\": \"Yes, use the register keyword to store the output and access it using variables like result.stdout.\"\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>The command module in Ansible runs commands on a target host. Unlike the shell module, it executes the command directly without invoking a shell. This ensures a higher level of &hellip; <\/p>\n","protected":false},"author":1,"featured_media":5708,"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-5707","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\/5707","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=5707"}],"version-history":[{"count":3,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/posts\/5707\/revisions"}],"predecessor-version":[{"id":6681,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/posts\/5707\/revisions\/6681"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/media\/5708"}],"wp:attachment":[{"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/media?parent=5707"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/categories?post=5707"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/linuxbuz.com\/wp-json\/wp\/v2\/tags?post=5707"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}