Bootstrap

ansible 常用模块

ansible 常用模块

一、ansible常用模块使用详解

ansible常用模块有:

  • ping
  • yum
  • template
  • copy
  • user
  • group
  • serviceb
  • raw
  • command
  • shell
  • script

ansible常用模块raw、command、shell的区别:

  • shell模块调用的/bin/sh指令执行
  • command模块不是调用的shell的指令,所以没有bash的环境变量
  • raw很多地方和shell类似,更多的地方建议使用shell和command模块。

二、ansible常用模块之ping

ping模块用于检查指定节点机器是否连通,用法很简单,不涉及参数,主机如果在线,则回复pong

[root@localhost ~]# ansible all -m ping
192.168.153.130 | SUCCESS => {
   
    "ansible_facts": {
   
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

三、ansible常用模块之command

command模块用于在远程主机上执行命令,ansible默认就是使用command模块。

在受控主机上创建文件
[root@localhost ansible]# ansible all -m command -a 'touch abc'
[WARNING]: Consider using the file module with state=touch rather than running 'touch'.  If you need to use command because file is insufficient you can add 'warn: false' to this command task
or set 'command_warnings=False' in ansible.cfg to get rid of this message.
192.168.153.130 | CHANGED | rc=0 >>

查看受控主机root家目录
[root@localhost ansible]# ansible all -m command -a 'ls /root'
192.168.153.130 | CHANGED | rc=0 >>
abc
anaconda-ks.cfg

command模块不支持管道符,不支持重定向
[root@localhost ansible]# ansible all  -a "echo 'hello world' > /root/abc"
192.168.153.130 | CHANGED | rc=0 >>
hello world > /root/abc
[root@localhost ansible]# ansible all  -a 'cat /root/abc'
192.168.153.130 | CHANGED | rc=0 >>

[root@localhost ansible]#  ansible all -a 'ps -ef|grep vsftpd'
192.168.153.130 | FAILED | rc=1 >>
error: unsupported SysV option

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).non-zero return code

四、ansible常用模块之raw

raw模块用于在远程主机上执行命令,其支持管道符与重定向

支持重定向
[root@localhost ansible]# ansible all -m raw  -a "echo 'hello world' > /root/abc"
192.168.153.130 | CHANGED | rc=0 >>
Shared connection to 192.168.153.130 closed.

[root@localhost ansible]# ansible all -m raw  -a 'cat /root/abc'
192.168.153.130 | CHANGED | rc=0 >>
hello world
Shared connection to 192.168.153.130 closed.

支持管道符
[root@localhost ansible]# ansible all -m raw  -a 'cat /root/abc|grep -Eo hello'
192.168.153.130 | CHANGED | rc=0 >>
hello
Shared connection to 192.168.153.130 closed.

五、ansible常用模块之shell

shell模块用于在受控机上执行受控机上的脚本,亦可直接在受控机上执行命令。
shell模块亦支持管道与重定向。

查看受控机上的脚本
[root@localhost ~]# ls
anaconda-ks.cfg  test.sh

使用shell模块在受控机上执行受控机上的脚本
[root@localhost ~]# ansible all -m shell -a '/bin/bash test.sh  &> /root/abc'
192.168.153
;