
转载说明:如果您喜欢这篇文章并打算转载它,请私信作者取得授权。感谢您喜爱本文,请文明转载,谢谢。
在继《关于Ansible的模块 ①》、《关于Ansible的模块 ②》、《关于Ansible的模块 ③》与《关于Ansible的模块 ④》、《关于ansible的模块 ⑤》与《关于ansible的模块 ⑥》之后,继续学习Ansible常用模块之通用模块。
command模块
ansible的默认模块是command,可以使用-m command指定使用command模块也可以直接省略。
command在远程节点上执行命令和shell模块类似,但不支持$HOME、"<"、">"、"|"、";"、"&"等操作。
1. 常用参数
|-------------------|---------|-----------------------------|
| 参数 | 默认值 | 含义 |
| cmd | null | 要运行的命令 |
| chdir | null | 在运行命令之前,先进入该目录 |
| creates | null | 如文件存在,则不运行此步骤 |
| removes | null | 如文件存在,则运行此步骤 |
| argv | null | 以list而非string模式传递命令 |
| free_form | null | shell模块接受一个自由形式的命令作为字符串来运行 |
| stdin | null | 将命令的stdin直接设置为指定的值 |
| stdin_add_newline | true | 是否向标准输入数据追加换行符 |
| strip_empty_ends | true | 在结果中去除 stdout/stderr 末尾的空行。 |
| warn | | 是否启用任务告警 |
2. 使用示例
2.1 简单执行命令
ansible all -m command -a "free -h"
ansible all -a "free -h" #省略-m参数默认就使用command模块

2.2 command模块与shell模块一样支持执行命令前更换目录
ansible all -m command -a "chdir=/tmp cat shell.txt"

2.3 不支持">"等符号
ansible all -m command -a 'echo "this is command test">/tmp/cmd.txt'

script模块
script模块可以帮助在远程主机上执行ansible主机本地的脚本,脚本不需要拷贝到远程主机上。
1. 常用参数
|------------|---------|----------------------|
| 参数 | 默认值 | 含义 |
| cmd | null | 要运行的命令 |
| chdir | null | 在运行命令之前,先进入该目录 |
| creates | null | 如远程主机上某文件存在,则不执行该步骤 |
| removes | null | 如远程主机上某文件不存在,则不执行该步骤 |
| decrypt | true | 控制使用vault自动解密源文件。 |
| executable | null | 调用脚本的可执行文件的名称或路径。 |
| free_form | null | 本地脚本文件的路径,后跟可选参数。 |
2. 使用示例
2.1 执行远程主机脚本
ansible all -m script -a 'chdir=/tmp test.sh'

2.2 如果远程主机上存在文件/tmp/1.txt,则不执行/tmp/test.sh
ansible all -m script -a 'creates=/tmp/1.txt /tmp/test.sh'

反之,如果远程主机上不存在/tmp/1.txt,就会执行脚本/tmp/test.sh:

2.3 如果远程主机上不存在文件文件/tmp/1.txt,则不执行/tmp/test.sh
ansible all -m script -a 'removes=/tmp/1.txt /tmp/test.sh'

反之,如果远程主机上存在/tmp/1.txt,就会执行脚本/tmp/test.sh:
