Ansible 模块 —— 对被控主机检查是否可达和执行 Shell 命令

对被控主机检查是否可达和执行命令

检测主机网络连通性

ansible.builtin.ping

  • data:模块执行成功时返回的内容(默认为 pong,当 data=crash 时模块会始终按失败处理)
- name: Host test
  ansible.builtin.ping:
    data: "Host OK!"

- name: Induce an exception to see what happens
  ansible.builtin.ping:
    data: "crash"

执行 Shell 命令

所有和执行 Shell 命令有关的模块在使用的时候状态始终是 changed 状态,所以原则上讲能用 Ansible 模块干的事情就不要用 Shell 相关模块去做。

执行 Shell 命令的模块有三种:

  • ansible.builtin.raw
  • ansible.builtin.command
  • ansible.builtin.shell
特性 command shell raw
依赖 Python ✅ 需要 ✅ 需要 ❌ 不需要
使用 Shell 环境 ❌ 不使用 /bin/sh,直接执行命令 ✅ 使用 /bin/sh/bin/bash ✅ 使用 /bin/sh
支持管道/重定向 ❌ 不支持 ✅ 支持 ✅ 支持(但无 Ansible 封装)
支持 shell 特性 ❌ 不支持变量、通配符、重定向等 ✅ 支持 ✅ 支持(不推荐复杂逻辑)
安全性 ✅ 更安全(避免命令注入) ⚠️ 较不安全(命令需转义/小心注入) ⚠️ 原始方式(不建议常用)
返回值结构 ✅ 标准格式 ✅ 标准格式 ❌ 基本结构,stdout/stderr 为主
适用场景 日常命令(如 mkdir、ls、cp) 脚本执行、管道、变量操作 初始化环境、无 Python 的机器

ansible.builtin.command

参数名 类型 默认值 说明
argv list null 命令及其参数组成的列表。
chdir string null 执行命令前切换到的目录,相当于先 cd
cmd string null 要执行的命令字符串(不支持管道、重定向等 shell 特性)。
creates path null 如果指定路径存在,则跳过该命令(用于幂等)。
expand_argument_vars bool false 是否展开命令参数中的变量(实验性功能)。
free_form string null 兼容旧写法,表示命令本身;不建议直接使用。
removes path null 如果指定路径不存在,则跳过该命令(用于幂等)。
stdin string null 提供给命令的标准输入内容。
stdin_add_newline bool true 是否自动为 stdin 内容末尾添加换行符。
strip_empty_ends bool true 是否移除输出中的结尾空行。

常用选项:

参数名 类型 默认值 说明
argv list null 命令及其参数组成的列表。
chdir string null 执行命令前切换到的目录,相当于先 cd
cmd string null 要执行的命令字符串(不支持管道、重定向等 shell 特性)。
creates path null 如果指定路径存在,则跳过该命令(用于幂等)。
removes path null 如果指定路径不存在,则跳过该命令(用于幂等)。

argvcmd 二选一。

- 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

参数名 类型 默认值 说明
executable string null 指定用于执行命令的 shell 路径,需为绝对路径(如 /bin/bash)。当使用 become(权限提升)时,若未指定将使用默认 shell。适用于想强制使用某种 shell 的场景。
free_form string null 并非实际参数字段。表示模块支持直接写命令而不是结构化参数(例如 - command: uptime),是为了简洁写法兼容设计。通常用户无需显式使用该名。
- 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

要使用 executableargs 不能省略。

ansible.builtin.shell

参数名 类型 默认值 说明
chdir string null 在运行命令前切换到指定目录,相当于 cd 后再执行。
cmd string null 要执行的命令字符串。支持所有 shell 特性,如管道、重定向、变量等。
creates path null 如果指定路径存在,则跳过命令执行(用于幂等控制)。
executable string null 用于执行命令的 shell 路径,默认根据系统环境选择(如 /bin/sh)。可指定为 /bin/bash 等以支持高级 shell 特性。
free_form string null 表示可以直接写命令(不是显式参数),用于简写任务。非显式使用字段。
removes path null 如果指定路径不存在,则跳过命令执行(用于幂等控制)。
stdin string null 传递给命令的标准输入内容,适合交互命令或脚本输入。
stdin_add_newline bool true 是否在 stdin 内容末尾自动添加换行符。

常用选项:

参数名 类型 默认值 说明
chdir string null 在运行命令前切换到指定目录,相当于 cd 后再执行。
cmd string null 要执行的命令字符串。支持所有 shell 特性,如管道、重定向、变量等。
creates path null 如果指定路径存在,则跳过命令执行(用于幂等控制)。
removes path null 如果指定路径不存在,则跳过命令执行(用于幂等控制)。

使用 executable 时要用 args

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

关于 command 和 shell 的区别

ansible.builtin.commandansible.builtin.shell 的区别就是后者会将管道符重定向等符号(如 ||&&;&|)等特殊符号解析成 Shell 的语法特性。

举个例子:

ansible.builtin.command 模块会将 ; 符号当成普通符号处理,所以只会打印 ; rm -rf /tmp/testdir

---
- 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 }}"

输出:

[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

ansible.builtin.shell 模块会将 ; 按照 Shell 方式的处理,所以会先执行 echo 命令,然后在执行 rm -rf /tmp/testdir

---
- 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 }}"

输出:

[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

执行脚本

ansible.builtin.script

参数名 类型 默认值 说明
cmd str 本地脚本路径和参数,例:files/setup.sh --force。和 free_form 实际上是一回事。
free_form str 模块的主参数,用于定义脚本路径及其参数。等价于 cmd,是 Ansible 的特殊写法。
chdir str 在远程节点上运行脚本前,切换到指定目录。
creates str 如果远程节点上已存在指定文件,则跳过执行脚本。用于幂等性控制。
removes str 如果远程节点上已存在指定文件,则运行脚本;运行成功后会删除该文件。与 creates 相反,常用于触发型脚本。
executable str 使用哪个解释器运行脚本,如 /bin/bash/usr/bin/python3 等。默认自动识别。
decrypt bool true 如果脚本是用 Ansible Vault 加密的,这个参数控制是否自动解密。

常用参数:

参数名 类型 默认值 说明
cmd str 本地脚本路径和参数,例:files/setup.sh --force。和 free_form 实际上是一回事。
chdir str 在远程节点上运行脚本前,切换到指定目录。
creates str 如果远程节点上已存在指定文件,则跳过执行脚本。用于幂等性控制。
removes str 如果远程节点上已存在指定文件,则运行脚本;运行成功后会删除该文件。与 creates 相反,常用于触发型脚本。
- 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
Ansible 模块 —— 对被控主机检查是否可达和执行 Shell 命令
https://www.linuxstudynotes.com/2025/04/30/ansible-%e6%a8%a1%e5%9d%97/ansible-%e6%a8%a1%e5%9d%97-%e5%af%b9%e8%a2%ab%e6%8e%a7%e4%b8%bb%e6%9c%ba%e6%a3%80%e6%9f%a5%e6%98%af%e5%90%a6%e5%8f%af%e8%be%be%e5%92%8c%e6%89%a7%e8%a1%8c-shell-%e5%91%bd%e4%bb%a4/
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇