How to run commands on target hosts with Ansible command module

AnsibleAnsibleBeginner
Practice Now

Introduction

Ansible is a powerful IT automation tool that simplifies the management of remote systems. In this tutorial, we will explore the Ansible command module, which allows you to execute commands on target hosts. You will learn the basics of command execution, as well as advanced techniques to enhance your Ansible workflows.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL ansible(("`Ansible`")) -.-> ansible/ModuleOperationsGroup(["`Module Operations`"]) ansible(("`Ansible`")) -.-> ansible/PlaybookEssentialsGroup(["`Playbook Essentials`"]) ansible/ModuleOperationsGroup -.-> ansible/shell("`Execute Shell Commands`") ansible/ModuleOperationsGroup -.-> ansible/script("`Run Scripts`") ansible/PlaybookEssentialsGroup -.-> ansible/playbook("`Execute Playbook`") ansible/ModuleOperationsGroup -.-> ansible/command("`Execute Commands`") subgraph Lab Skills ansible/shell -.-> lab-415740{{"`How to run commands on target hosts with Ansible command module`"}} ansible/script -.-> lab-415740{{"`How to run commands on target hosts with Ansible command module`"}} ansible/playbook -.-> lab-415740{{"`How to run commands on target hosts with Ansible command module`"}} ansible/command -.-> lab-415740{{"`How to run commands on target hosts with Ansible command module`"}} end

Understanding Ansible Command Module

Ansible is a powerful open-source automation tool that allows you to manage and configure your infrastructure across multiple hosts. The Ansible Command module is one of the core modules in Ansible that enables you to execute arbitrary commands on remote hosts.

The Ansible Command module provides a simple and straightforward way to run commands on target hosts. It allows you to execute shell commands, scripts, or any other executable file on the remote system. This module is particularly useful when you need to perform ad-hoc tasks, troubleshoot issues, or execute custom commands on your infrastructure.

To use the Ansible Command module, you need to define the command parameter in your Ansible playbook or ad-hoc command. The command parameter specifies the command you want to execute on the remote host. For example:

- name: Execute a command on remote host
  command: uptime
  register: uptime_result
  become: yes

In this example, the command parameter is set to uptime, which will execute the uptime command on the remote host. The register parameter is used to capture the output of the command, and the become parameter is set to yes to run the command with elevated privileges (if required).

The Ansible Command module also supports various options, such as:

  • creates: Specifies a file that must exist before running the command.
  • removes: Specifies a file that must not exist before running the command.
  • chdir: Changes the current working directory to the specified path before executing the command.
  • stdin: Passes the specified string to the command via standard input.
  • warn: Controls whether to show a warning if the command could potentially change an important file.

By understanding the Ansible Command module, you can efficiently execute commands on your remote hosts, automate repetitive tasks, and streamline your infrastructure management processes.

Executing Commands on Remote Hosts

Basic Command Execution

To execute a command on a remote host using the Ansible Command module, you can use the following basic syntax:

- name: Execute a command on remote host
  command: <command>
  register: <result_variable>
  become: yes

In this example, <command> is the actual command you want to execute on the remote host, and <result_variable> is the variable that will store the output of the command. The become parameter is set to yes to run the command with elevated privileges (if required).

For example, to check the uptime of a remote host:

- name: Check uptime of remote host
  command: uptime
  register: uptime_result
  become: yes

The output of the uptime command will be stored in the uptime_result variable, which you can then use in your playbook or ad-hoc command.

Handling Command Errors

By default, the Ansible Command module will fail if the executed command returns a non-zero exit code. You can handle command errors by using the ignore_errors parameter:

- name: Execute a command on remote host
  command: <command>
  register: <result_variable>
  ignore_errors: yes

This will allow the playbook to continue executing even if the command fails.

Capturing Command Output

You can capture the output of a command by using the register parameter, as shown in the previous examples. The output will be stored in the specified variable, which you can then use in your playbook or ad-hoc command.

For example, to capture the output of the uptime command and print it:

- name: Check uptime of remote host
  command: uptime
  register: uptime_result
  become: yes

- name: Print uptime
  debug:
    msg: "{{ uptime_result.stdout }}"

This will print the output of the uptime command to the console.

By understanding the basics of executing commands on remote hosts with the Ansible Command module, you can effectively automate a wide range of tasks in your infrastructure.

Advanced Command Execution Techniques

Conditional Command Execution

Sometimes, you may want to execute a command only if a certain condition is met. You can use the when clause to conditionally execute commands in your Ansible playbook:

- name: Execute command if condition is met
  command: <command>
  when: <condition>
  register: <result_variable>
  become: yes

In this example, the <command> will only be executed if the <condition> is true.

For instance, to execute the free command only if the system has less than 20% of free memory:

- name: Check free memory
  command: free -m
  register: memory_result
  become: yes

- name: Execute command if free memory is less than 20%
  command: <command_to_execute>
  when: (memory_result.stdout_lines[1].split()[3]|int / memory_result.stdout_lines[1].split()[1]|int * 100) < 20
  register: <result_variable>
  become: yes

Looping Over Commands

You can also use loops to execute multiple commands in a single task. The Ansible Command module supports the loop parameter for this purpose:

- name: Execute multiple commands
  command: "{{ item }}"
  loop:
    - <command1>
    - <command2>
    - <command3>
  register: <result_variable>
  become: yes

In this example, the specified commands (<command1>, <command2>, and <command3>) will be executed one by one, and the output will be stored in the <result_variable>.

Handling Command Timeouts

By default, Ansible will wait indefinitely for a command to complete. However, you can set a timeout for the command execution using the timeout parameter:

- name: Execute command with timeout
  command: <command>
  timeout: 60
  register: <result_variable>
  become: yes

In this example, the command will be terminated if it takes longer than 60 seconds to complete.

By mastering these advanced command execution techniques, you can further enhance your Ansible automation capabilities and handle a wide range of scenarios in your infrastructure management.

Summary

This Ansible tutorial has provided a comprehensive guide on using the command module to execute commands on remote hosts. By understanding the fundamentals and exploring advanced techniques, you can leverage Ansible's capabilities to streamline your IT operations and improve efficiency across your infrastructure.

Other Ansible Tutorials you may like