2.ansible常用的模块01

1.模块?

  模块实际上就是脚本,是ansible调用的对象,主要是用来通过调用它去远程执行某些命令功能。

2.常用的模块

  2.1 shell模块

     ansible默认的模块是command,其中shell模块与command模块区别:

     1. command模块的命令不启动shell,直接通过ssh执行命令

     2.command不支持bash的特性,如管道和重定向等功能

     3.所有需要调用shell的功能都无法使用command模块

  另外shel模块会启动shell执行命令,不可以使用shell模块执行交互命令,如vim、top等  

复制代码
[root@db04 ansible]# ansible test -m command -a 'ps|wc -l'        # 报错
db02 | FAILED | rc=2 >>
[Errno 2] No such file or directory
db01 | FAILED | rc=2 >>
[Errno 2] No such file or directory
[root@db04 ansible]# ansible test -m shell  -a 'ps |wc -l'        # shell模块可以
db01 | CHANGED | rc=0 >>
6
db02 | CHANGED | rc=0 >>
6
复制代码

  当执行shell模块后,退出ssh后所有状态失效。

  • chdir  
[root@db04 ansible]# ansible db01 -m shell -a "chdir=/tmp touch my.txt"

  这里可以通过chdir(该参数用于切换工作目录)执行要到哪个目录下创建文件。

  • creates、removes  支持判断

     creates文件名:文件存在,不执行shell命令

     removes 文件名:文件不存在,不执行shell命令

[root@db04 ansible]# ansible test -m shell -a "ssh-keygen -f ~/.ssh/id_rsa -N '' creates=~/.ssh/id_rsa"
# 如果已经有密钥文件id_rsa,则不创建密钥(skip跳过)
[root@db04 ansible]# ansible test -m shell "unzip xxx.zip removes=/bin/unzip"
# 如果没有安装unzip软件包,则不执行解压命令(skip)

 

 2.2 script模块

     script允许在本地写脚本,拷贝到被管理端并执行脚本,脚本不一定非要是shell脚本(也可以是python、perl脚本),可以没有-x权限

   script模块主要用来执行脚本的

[root@db04 ansible]# ansible test -m script -a "./t.sh"

# 注意脚本执行过程中都必须是非交互式的

小结:

  • command模块、shell模块区别?

     command不开启shell解释器,直接通过ssh执行命令,不支持bash一些特性,如重定向

  • script模块

    可以将提前编写好的脚本发送给远程主机,批量执行一组命令

 

   

posted on   太白金星有点烦  阅读(59)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示