当前位置: 首页 > news >正文

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

特性

commandshellraw
依赖 Python

需要

需要

不需要

使用 Shell 环境

不使用 /bin/sh,直接执行命令

使用 /bin/sh 或 /bin/bash

使用 /bin/sh

支持管道/重定向

不支持

支持

支持(但无 Ansible 封装)

支持 shell 特性

不支持变量、通配符、重定向等

支持

支持(不推荐复杂逻辑)

安全性

更安全(避免命令注入)

较不安全(命令需转义/小心注入)

原始方式(不建议常用)

返回值结构

标准格式

标准格式

基本结构,stdout/stderr 为主

适用场景

日常命令(如 mkdir、ls、cp)

脚本执行、管道、变量操作

初始化环境、无 Python 的机器

ansible.builtin.command

参数名

类型

默认值

说明

argvlistnull

命令及其参数组成的列表。

chdirstringnull

执行命令前切换到的目录,相当于先 cd

cmdstringnull

要执行的命令字符串(不支持管道、重定向等 shell 特性)。

createspathnull

如果指定路径存在,则跳过该命令(用于幂等)。

expand_argument_varsboolfalse

是否展开命令参数中的变量(实验性功能)。

free_formstringnull

兼容旧写法,表示命令本身;不建议直接使用。

removespathnull

如果指定路径不存在,则跳过该命令(用于幂等)。

stdinstringnull

提供给命令的标准输入内容。

stdin_add_newlinebooltrue

是否自动为 stdin 内容末尾添加换行符。

strip_empty_endsbooltrue

是否移除输出中的结尾空行。

常用选项:

参数名

类型

默认值

说明

argvlistnull

命令及其参数组成的列表。

chdirstringnull

执行命令前切换到的目录,相当于先 cd

cmdstringnull

要执行的命令字符串(不支持管道、重定向等 shell 特性)。

createspathnull

如果指定路径存在,则跳过该命令(用于幂等)。

removespathnull

如果指定路径不存在,则跳过该命令(用于幂等)。

argv 和 cmd 二选一。

- 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

参数名

类型

默认值

说明

executablestringnull指定用于执行命令的 shell 路径

,需为绝对路径(如 /bin/bash)。当使用 become(权限提升)时,若未指定将使用默认 shell。适用于想强制使用某种 shell 的场景。

free_formstringnull

并非实际参数字段。表示模块支持直接写命令而不是结构化参数(例如 - 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

要使用 executable 时 args 不能省略。

ansible.builtin.shell

参数名

类型

默认值

说明

chdirstringnull

在运行命令前切换到指定目录,相当于 cd 后再执行。

cmdstringnull

要执行的命令字符串。支持所有 shell 特性,如管道、重定向、变量等。

createspathnull

如果指定路径存在,则跳过命令执行(用于幂等控制)。

executablestringnull

用于执行命令的 shell 路径,默认根据系统环境选择(如 /bin/sh)。可指定为 /bin/bash 等以支持高级 shell 特性。

free_formstringnull

表示可以直接写命令(不是显式参数),用于简写任务。非显式使用字段。

removespathnull

如果指定路径不存在,则跳过命令执行(用于幂等控制)。

stdinstringnull

传递给命令的标准输入内容,适合交互命令或脚本输入。

stdin_add_newlinebooltrue

是否在 stdin 内容末尾自动添加换行符。

常用选项:

参数名

类型

默认值

说明

chdirstringnull

在运行命令前切换到指定目录,相当于 cd 后再执行。

cmdstringnull

要执行的命令字符串。支持所有 shell 特性,如管道、重定向、变量等。

createspathnull

如果指定路径存在,则跳过命令执行(用于幂等控制)。

removespathnull

如果指定路径不存在,则跳过命令执行(用于幂等控制)。

使用 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.command 和 ansible.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

参数名

类型

默认值

说明

cmdstr

本地脚本路径和参数,例:files/setup.sh --force。和 free_form 实际上是一回事。

free_formstr

模块的主参数,用于定义脚本路径及其参数。等价于 cmd,是 Ansible 的特殊写法。

chdirstr

在远程节点上运行脚本前,切换到指定目录。

createsstr

如果远程节点上已存在指定文件,则跳过执行脚本。用于幂等性控制。

removesstr

如果远程节点上已存在指定文件,则运行脚本;运行成功后会删除该文件。与 creates 相反,常用于触发型脚本。

executablestr

使用哪个解释器运行脚本,如 /bin/bash/usr/bin/python3 等。默认自动识别。

decryptbooltrue

如果脚本是用 Ansible Vault 加密的,这个参数控制是否自动解密。

常用参数:

参数名

类型

默认值

说明

cmdstr

本地脚本路径和参数,例:files/setup.sh --force。和 free_form 实际上是一回事。

chdirstr

在远程节点上运行脚本前,切换到指定目录。

createsstr

如果远程节点上已存在指定文件,则跳过执行脚本。用于幂等性控制。

removesstr

如果远程节点上已存在指定文件,则运行脚本;运行成功后会删除该文件。与 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

相关文章:

  • 电池的寿命(不清楚是什么类型/虽然有标明是贪心)
  • DAX 权威指南1:DAX计算、表函数与计算上下文
  • JS DOM操作与事件处理从入门到实践
  • Flink和Spark的选型
  • 【vue】vuex实现组件间数据共享 vuex模块化编码 网络请求
  • 使用 Jackson 在 Java 中解析和生成 JSON
  • C.printf 函数基础
  • 大模型的RAG技术系列(三)
  • linux和linux 、linux和windows实现文件复制笔记
  • 基于ssm+mysql的快递管理系统(含LW+PPT+源码+系统演示视频+安装说明)
  • C语言复习--柔性数组
  • Vite Proxy配置详解:从入门到实战应用
  • Activity动态切换Fragment
  • 养生:为健康生活添彩
  • 【Linux第三章】vim
  • 达索PLM系统是什么?有什么用?
  • 亿级流量系统架构设计与实战(六)
  • 【MySQL】事务(重点)
  • 【计算机视觉】OpenCV实战项目:FunnyMirrors:基于OpenCV的实时哈哈镜效果实现技术解析
  • PyTorch API 9 - masked, nested, 稀疏, 存储
  • 马鞍山市原常务副市长黄化锋一审获刑11年,涉案金额三千余万元
  • 人民日报读者点题·共同关注:今天我们为什么还需要图书馆?
  • 王毅同巴基斯坦副总理兼外长达尔通电话
  • 俄罗斯今日将举行“胜利日”阅兵,有何看点?
  • 奥利弗·斯通回顾越战50周年:我们不善于总结历史教训
  • 美联储连续第三次维持利率不变,警示关税影响