Ansible provides several modules for executing commands and scripts on remote hosts. This section details the command and script modules.
The command Module
The command module is Ansible's default. It executes commands on remote nodes. Unlike the shell module, it does not support shell features like redirection (>), pipes (|), or variable expansion ($HOME).
Common Parameters:
cmd: The command to execute (string).chdir: Change to this directory before running the command (string).creates: If this file exists on the remote host, the command will not be executed (string).removes: If this file does NOT exist on the remote host, the command will not be executed (string).argv: Pass the command as a list of strings instead of a single string.free_form: Similar toshellmodule's free-form command input.stdin: Provide input to the command's standard input (string).stdin_add_newline: Append a newline character tostdindata (boolean, default:true).strip_empty_ends: Remove empty lines from the beginning and end ofstdoutandstderr(boolean, default:true).warn: Whether to enable task warnings (boolean).
Usage Examples:
Execute a command:
- name: Run 'free -h' command
ansible.builtin.command: free -h
Change directory before exceuting:
- name: Change directory and list file contents
ansible.builtin.command: "chdir=/tmp cat shell.txt"
Attempting to use redirection, which is not supported by command:
- name: Attempt redirection (will fail)
ansible.builtin.command: "echo 'this is a test' > /tmp/cmd.txt"
The script Module
The script module allows you to run scripts located on your Ansible control node directly on remote hosts without manually copying them first.
Common Parameters:
cmd: The command to execute (string).chdir: Change to this directory before running the script (string).creates: If this file exists on the remote host, the script will not be executed (string).removes: If this file does NOT exist on the remote host, the script will not be executed (string).decrypt: Whether to automatically decrypt vault-encrypted scripts (boolean, default:true).executable: The interpreter to use for running the script (e.g.,/bin/bash,/usr/bin/python) (string, default: inferred from script name).free_form: The path to the local script file on the control node, followed by optional arguments.
Usage Examples:
Execute a local script on remote hosts:
- name: Execute a local script
ansible.builtin.script: /path/to/local/script.sh arg1 arg2
Execute a script only if a file does not exist on the remote host:
- name: Execute script if /tmp/1.txt does not exist
ansible.builtin.script:
cmd: /tmp/test.sh
creates: /tmp/1.txt
Execute a script only if a file exists on the remote host:
- name: Execute script if /tmp/1.txt exists
ansible.builtin.script:
cmd: /tmp/test.sh
removes: /tmp/1.txt