关于Ansible模块 ⑥

转载说明:如果您喜欢这篇文章并打算转载它,请私信作者取得授权。感谢您喜爱本文,请文明转载,谢谢。


内容在继《关于Ansible的模块 ①》《关于Ansible的模块 ②》《关于Ansible的模块 ③》《关于Ansible的模块 ④》《关于ansible的模块 ⑤》之后,继续学习Ansible常用模块之shell模块。

shell模块,在远程节点上通过/bin/sh执行命令。如果一个操作可以通过yum、copy实现,那么建议不要使用shell、command这样通用的命令模块。因为通用的命令模块不会根据具体操作的特点进行状态判断,所以当没有必要重新再执行的时候,它还是会重新执行一遍。

shell模块支持$HOME、、"<"、">"、"|"、";"、"&"等操作。

1. 常用参数

|-------------------|---------|-------------------------------|
| 参数 | 默认值 | 含义 |
| cmd | null | 指定要运行的命令 |
| chdir | null | 在运行命令之前,先进入该目录 |
| creates | null | 如文件存在,则不会运行该步骤 |
| removes | null | 如文件不存在,则不会运行该步骤 |
| executable | null | 更改用于执行命令的shell,需要指定可执行文件的绝对路径 |
| free_form | null | shell模块接受一个自由形式的命令作为字符串来运行 |
| stdin | null | 将命令的stdin直接设置为指定的值 |
| stdin_add_newline | | 是否向标准输入数据追加换行符 |
| warn | | 是否启用任务告警 |

2. 使用示例

2.1 查看远程主机文件是否存在

复制代码
ansible all -m shell -a "ls /tmp|grep test.sh"

2.2 查看文件内容:

复制代码
ansible all -m shell -a "cat /tmp/test.sh"

2.3 查看远程主机IP

复制代码
ansible all -m shell -a "ifconfig ens32|awk -F \"[ ]+\" 'NR==2{print \$3}'"

2.4 创建一个文件并写入内容

复制代码
ansible all -m shell -a 'echo "this is shell test">>/tmp/shell.txt'

2.5 执行远程主机指定脚本

复制代码
ansible all -m shell -a "/tmp/test.sh"

2.6 执行命令前更换目录

复制代码
ansible all -m shell -a 'chdir=/tmp echo "this is shell test">shell.txt'

未完待续......

感谢您的阅读与分享!

相关推荐
阎*水1 天前
Ansible 核心要点总结
ansible
小安运维日记1 天前
RHCA - DO374 | Day09:自定义内容集和执行环境
linux·运维·服务器·系统架构·ansible·改行学it
-dcr1 天前
48.Ansible自动化
自动化·ansible·dubbo
課代表1 天前
bat 批处理脚本中的字符串
字符串·脚本·命令行·bat·批处理·字符串截取·延迟变量
神秘面具男032 天前
Ansible Playbook 编写与运行
服务器·网络·ansible
随风语2 天前
ansible
运维·自动化·ansible
tianyuanwo2 天前
纵深防御:构建安全高效的 Ansible 自动化运维体系
运维·安全·ansible
阿方索2 天前
Ansible
ansible
成为你的宁宁2 天前
【Jenkins 与 Ansible 集成指南:从优势解析到实战落地(含本机配置、插件安装、工具配置及命令 / 剧本两种 Jenkins 调用方式全流程】
ansible·jenkins
ice_bird2 天前
Ansible一键部署k8s1.28.2集群
kubernetes·ansible