Ansible Modules for Host Connectivity and Command Execution

Check Host Reachability and Execute Commands

Check Host Network Connectivity

<span>ansible.builtin.ping</span>:

  • <span>data</span>: The content returned when the module executes successfully (default is <span>pong</span>, and when <span>data=crash</span>, the module will always be treated as a failure)
- name: Host test  ansible.builtin.ping:    data: "Host OK!"
- name: Induce an exception to see what happens  ansible.builtin.ping:    data: "crash"

Execute Shell Commands

All modules related to executing shell commands always have a status of changed, so in principle, if something can be done with Ansible modules, do not use shell-related modules.

There are three modules for executing shell commands:

  • <span>ansible.builtin.raw</span>
  • <span>ansible.builtin.command</span>
  • <span>ansible.builtin.shell</span>
Feature <span>command</span> <span>shell</span> <span>raw</span>
Depends on Python Required Required Not required
Uses Shell Environment Does not use <span>/bin/sh</span>, executes commands directly Uses <span>/bin/sh</span> or <span>/bin/bash</span> Uses <span>/bin/sh</span>
Supports Pipes/Redirection Does not support Supports Supports (but without Ansible encapsulation)
Supports Shell Features Does not support variables, wildcards, redirection, etc. Supports Supports (not recommended for complex logic)
Security Safer (avoids command injection) Less secure (commands need to be escaped/careful of injection) Raw method (not recommended for frequent use)
Return Value Structure Standard format Standard format Basic structure, primarily stdout/stderr
Applicable Scenarios Daily commands (e.g., mkdir, ls, cp) Script execution, piping, variable manipulation Initialize environment, machines without Python

ansible.builtin.command

Parameter Name Type Default Value Description
<span>argv</span> <span>list</span> null List of command and its parameters.
<span>chdir</span> <span>string</span> null Directory to change to before executing the command, equivalent to first <span>cd</span>.
<span>cmd</span> <span>string</span> null Command string to execute (does not support piping, redirection, etc. shell features).
<span>creates</span> <span>path</span> null If the specified path exists, skip this command (for idempotency).
<span>expand_argument_vars</span> <span>bool</span> <span>false</span> Whether to expand variables in command parameters (experimental feature).
<span>free_form</span> <span>string</span> null Compatible with old syntax, represents the command itself; not recommended for direct use.
<span>removes</span> <span>path</span> null If the specified path does not exist, skip this command (for idempotency).
<span>stdin</span> <span>string</span> null Standard input content provided to the command.
<span>stdin_add_newline</span> <span>bool</span> <span>true</span> Whether to automatically add a newline at the end of <span>stdin</span> content.
<span>strip_empty_ends</span> <span>bool</span> <span>true</span> Whether to remove trailing empty lines from output.

Common options:

Parameter Name Type Default Value Description
<span>argv</span> <span>list</span> null List of command and its parameters.
<span>chdir</span> <span>string</span> null Directory to change to before executing the command, equivalent to first <span>cd</span>.
<span>cmd</span> <span>string</span> null Command string to execute (does not support piping, redirection, etc. shell features).
<span>creates</span> <span>path</span> null If the specified path exists, skip this command (for idempotency).
<span>removes</span> <span>path</span> null If the specified path does not exist, skip this command (for idempotency).

<span>argv</span> and <span>cmd</span> are mutually exclusive.

- name: touch file1  ansible.builtin.command:    argv:    - /bin/touch    - testfile    - "&&"    - /bin/touch    - testfile1    chdir: /tmp
- name: touch file2  ansible.builtin.command:    cmd: "/bin/touch /tmp/testfile2"    creates: /tmp/testfile3

ansible.builtin.raw

Parameter Name Type Default Value Description
<span>executable</span> <span>string</span> null Specify the shell path used to execute the command, must be an absolute path (e.g., <span>/bin/bash</span>). When using <span>become</span> (privilege escalation), if not specified, the default shell will be used. Suitable for scenarios where you want to enforce a specific shell.
<span>free_form</span> <span>string</span> null Not an actual parameter field. Indicates that the module supports writing commands directly instead of structured parameters (e.g., <span>- command: uptime</span><code><span>), designed for concise syntax compatibility. Users typically do not need to use this name explicitly.</span>
- name: Bootstrap a host without python2 installed  ansible.builtin.raw: dnf install -y python2 python2-dnf libselinux-python
- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)  ansible.builtin.raw: cat < /tmp/*txt  args:    executable: /bin/bash

When using <span>executable</span>, <span>args</span> cannot be omitted.

ansible.builtin.shell

Parameter Name Type Default Value Description
<span>chdir</span> <span>string</span> null Change to the specified directory before running the command, equivalent to <span>cd</span> and then execute.
<span>cmd</span> <span>string</span> null Command string to execute. Supports all shell features, such as piping, redirection, variables, etc.
<span>creates</span> <span>path</span> null If the specified path exists, skip command execution (for idempotency control).
<span>executable</span> <span>string</span> null Shell path used to execute the command, default is selected based on the system environment (e.g., <span>/bin/sh</span>). Can be specified as <span>/bin/bash</span> etc. to support advanced shell features.
<span>free_form</span> <span>string</span> null Indicates that commands can be written directly (not explicit parameters), used for shorthand tasks. Not explicitly used field.
<span>removes</span> <span>path</span> null If the specified path does not exist, skip command execution (for idempotency control).
<span>stdin</span> <span>string</span> null Standard input content passed to the command, suitable for interactive commands or script input.
<span>stdin_add_newline</span> <span>bool</span> <span>true</span> Whether to automatically add a newline at the end of <span>stdin</span> content.

Common options:

Parameter Name Type Default Value Description
<span>chdir</span> <span>string</span> null Change to the specified directory before running the command, equivalent to <span>cd</span> and then execute.
<span>cmd</span> <span>string</span> null Command string to execute. Supports all shell features, such as piping, redirection, variables, etc.
<span>creates</span> <span>path</span> null If the specified path exists, skip command execution (for idempotency control).
<span>removes</span> <span>path</span> null If the specified path does not exist, skip command execution (for idempotency control).

When using <span>executable</span>, you must use <span>args</span>.

- name: Run command using bash  ansible.builtin.shell:    cmd: echo qwe > testfile2    chdir: /tmp    removes: testfile2  args:    executable: /bin/bash

Difference Between Command and Shell

<span>ansible.builtin.command</span> and <span>ansible.builtin.shell</span> differ in that the latter will parse special symbols such as pipe, redirection, etc. (like <span>||</span>, <span>&&</span>, <span>;</span>, <span>&</span>, <span>|</span>) as shell syntax features.

For example:

<span>ansible.builtin.command</span> module will treat the <span>;</span> symbol as a normal symbol, so it will only print <span>; rm -rf /tmp/testdir</span>:

---- name: test  hosts: localhost  vars:    CMD: "; rm -rf /tmp/testdir"  tasks:  - name: Run command using bash    ansible.builtin.command:      cmd: echo {{ CMD }}    register: line  - name: Print    ansible.builtin.debug:      msg: "{{ line }}"

Output:

[root@awx-1 ansible]# ansible-playbook test.yml
PLAY [test] *********************************************************************************************************************************************************************
TASK [Run command using bash] ***************************************************************************************************************************************************changed: [localhost]
TASK [Print] ********************************************************************************************************************************************************************ok: [localhost] => {    "msg": {        "changed": true,        "cmd": [            "echo",            ";",            "rm",            "-rf",            "/tmp/testdir"        ],        "delta": "0:00:00.003449",        "end": "2025-04-19 23:59:19.959961",        "failed": false,        "msg": "",        "rc": 0,        "start": "2025-04-19 23:59:19.956512",        "stderr": "",        "stderr_lines": [],        "stdout": "; rm -rf /tmp/testdir",        "stdout_lines": [            "; rm -rf /tmp/testdir"        ]    }}
PLAY RECAP **********************************************************************************************************************************************************************localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

<span>ansible.builtin.shell</span> module will process the <span>;</span> according to shell processing, so it will first execute the <span>echo</span> command, and then execute <span>rm -rf /tmp/testdir</span>:

---- name: test  hosts: localhost  vars:    CMD: "; rm -rf /tmp/testdir"  tasks:  - name: Run shell using bash    ansible.builtin.shell:      cmd: echo {{ CMD }}    register: line  - name: Print    ansible.builtin.debug:      msg: "{{ line }}"

Output:

[root@awx-1 ansible]# ansible-playbook test.yml
PLAY [test] *********************************************************************************************************************************************************************
TASK [Run shell using bash] ***************************************************************************************************************************************************changed: [localhost]
TASK [Print] ********************************************************************************************************************************************************************ok: [localhost] => {    "msg": {        "changed": true,        "cmd": "echo ; rm -rf /tmp/testdir",        "delta": "0:00:00.006003",        "end": "2025-04-19 23:59:41.187245",        "failed": false,        "msg": "",        "rc": 0,        "start": "2025-04-19 23:59:41.181242",        "stderr": "",        "stderr_lines": [],        "stdout": "",        "stdout_lines": []    }}
PLAY RECAP **********************************************************************************************************************************************************************localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Execute Scripts

<span>ansible.builtin.script</span>

Parameter Name Type Default Value Description
<span>cmd</span> <span>str</span> None Local script path and parameters, e.g., <span>files/setup.sh --force</span>. Actually the same as <span>free_form</span>.
<span>free_form</span> <span>str</span> None Main parameter of the module, used to define the script path and its parameters. Equivalent to <span>cmd</span>, a special syntax of Ansible.
<span>chdir</span> <span>str</span> None Change to the specified directory before running the script on the remote node.
<span>creates</span> <span>str</span> None If the specified file already exists on the remote node, skip executing the script. Used for idempotency control.
<span>removes</span> <span>str</span> None If the specified file already exists on the remote node, run the script; after successful execution, it will delete the file. Opposite to <span>creates</span>, commonly used for trigger scripts.
<span>executable</span> <span>str</span> None Which interpreter to use to run the script, such as <span>/bin/bash</span>, <span>/usr/bin/python3</span>, etc. Default is auto-detected.
<span>decrypt</span> <span>bool</span> <span>true</span> If the script is encrypted with Ansible Vault, this parameter controls whether to automatically decrypt.

Common parameters:

Parameter Name Type Default Value Description
<span>cmd</span> <span>str</span> None Local script path and parameters, e.g., <span>files/setup.sh --force</span>. Actually the same as <span>free_form</span>.
<span>chdir</span> <span>str</span> None Change to the specified directory before running the script on the remote node.
<span>creates</span> <span>str</span> None If the specified file already exists on the remote node, skip executing the script. Used for idempotency control.
<span>removes</span> <span>str</span> None If the specified file already exists on the remote node, run the script; after successful execution, it will delete the file. Opposite to <span>creates</span>, commonly used for trigger scripts.
- name: Run a script with arguments (free form)  ansible.builtin.script: /some/local/script.sh --some-argument 1234
- name: Run a script with arguments (using 'cmd' parameter)  ansible.builtin.script:    cmd: /some/local/script.sh --some-argument 1234
- name: Run a script only if file.txt does not exist on the remote node  ansible.builtin.script: /some/local/create_file.sh --some-argument 1234  args:    creates: /the/created/file.txt
- name: Run a script only if file.txt exists on the remote node  ansible.builtin.script: /some/local/remove_file.sh --some-argument 1234  args:    removes: /the/removed/file.txt
- name: Run a script using an executable in a non-system path  ansible.builtin.script: /some/local/script  args:    executable: /some/remote/executable
- name: Run a script using an executable in a system path  ansible.builtin.script: /some/local/script.py  args:    executable: python3
- name: Run a Powershell script on a Windows host  script: subdirectories/under/path/with/your/playbook/script.ps1

Leave a Comment