Ansible Command Module Explained with Examples

Ansible-command-Module-Example

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 security because shell features like redirection, piping, or variable substitution are not supported.

Key Features:

  • Runs command in a non-interactive manner.
  • Does not process shell operators like |, &&, or $.
  • Can be used for tasks like checking system status, starting/stopping services, or managing simple configurations.

In this article, we’ll explore the Ansible command module with practical examples.

Basic Syntax

Here is the basic syntax:

- name: Task description
  hosts: target_host
  tasks:
    - name: Execute a command
      ansible.builtin.command:
        cmd: command-name

Explanation:

  • cmd: The command to be executed.
  • chdir: Changes the working directory before running the command.
  • creates: Specifies a file path; if the file exists, the command will not run.

Example 1: Basic Execution

This playbook run the uptime command to check the system’s uptime on the target host and displays the output with the debug module.

- name: Check system uptime
  hosts: all
  tasks:
    - name: Run uptime command
      ansible.builtin.command:
        cmd: uptime
      register: uptime_result

    - name: Display uptime output
      debug:
        msg: "System uptime: {{ uptime_result.stdout }}"

Example 2: Using Arguments in Commands

Run a command with additional arguments, such as listing detailed file information.

- name: List files in a directory
  hosts: all
  tasks:
    - name: List files in /etc
      ansible.builtin.command:
        cmd: ls -l /etc
      register: list_files_result

    - name: Display file list
      debug:
        msg: "Files in /etc:\n{{ list_files_result.stdout }}"

This playbook lists all files and directories in /etc in a detailed format.

Example 3: Creating Files Conditionally

Create a file only if it doesn’t already exist, and confirm the action.

- name: Conditionally create a file
  hosts: all
  tasks:
    - name: Create file if it doesn't exist
      ansible.builtin.command:
        cmd: touch /tmp/newfile.txt
        creates: /tmp/newfile.txt
      register: create_file_result

    - name: Display file creation status
      debug:
        msg: "File creation output: {{ create_file_result.stdout }}"

Here, the creates parameter ensures the command runs only if the specified file does not exist.

Example 4: Changing Directories Before Execution

Run a command in a specific directory.

- name: Run commands in a specific directory
  hosts: all
  tasks:
    - name: List files in /tmp
      ansible.builtin.command:
        cmd: ls -l
        chdir: /tmp
      register: directory_list_result

    - name: Display directory contents
      debug:
        msg: "Directory contents:\n{{ directory_list_result.stdout }}"

In this playbook, the chdir args changes the current working directory to /tmp before running the ls -l command.

Example 5: Combining Command with Loops

Run the same command on multiple files using a loop.

- name: Display file sizes
  hosts: all
  tasks:
    - name: Check file sizes in /tmp
      ansible.builtin.command:
        cmd: du -sh /tmp/{{ item }}
      with_items:
        - file1.txt
        - file2.log
        - dir1
      register: file_sizes_result

    - name: Display file size results
      debug:
        var: file_sizes_result.results | map(attribute='stdout') | join('\n')

Here, the task calculates the size of multiple files and directories in /tmp and displays the output.

Conclusion

The Ansible command module is a powerful tool for executing simple commands on remote systems. While it doesn’t provide the flexibility of the shell module, its security and simplicity make it an excellent choice for basic administrative tasks.

FAQs

1. Can I run commands as a specific user?

Yes, you can use the become directive in the playbook to run the command as a different user.

2. Does this Ansible Module support conditional execution?

Yes, you can use Ansible conditionals like when to control when a command runs.

3. Can I capture the output of a command ?

Yes, use the register keyword to store the output and access it using variables like result.stdout.

About Hitesh Jethva

Experienced Technical writer, DevOps professional with a demonstrated history of working in the information technology and services industry. Skilled in Game server hosting, AWS, Jenkins, Ansible, Docker, Kubernetes, Web server, Security, Proxy, Iptables, Linux System Administration, Domain Name System (DNS), and Technical Writing.

View all posts by Hitesh Jethva