MENU

Ansible 自动化(3)常见模块实例

January 1, 2018 • Read: 3985 • 应用搭建

1 ansible 常用模块

ansible-doc -l ;查看到当前 ansible 都支持哪些模块,

ansible-doc -s 模块名;查看该模块有哪些参数可以使用。

copy模块
file模块
cron模块
group模块
user模块





yum模块
service模块
script模块
ping模块
command模块
raw模块
get_url模块
synchronize模块

2 常见模块实例

copy 模块:

目的:把主控端/root目录下的a.sh文件拷贝到到指定节点上

命令:ansible 10.1.1.113 -m copy -a 'src=/root/a.sh dest=/tmp/'

file 模块:

目的:更改指定节点上/tmp/t.sh的权限为755,属主和属组为root

命令:ansible all -m file -a "dest=/tmp/t.sh mode=755 owner=root group=root"

cron 模块:
目的:在指定节点上定义一个计划任务,每隔 3 分钟到主控端更新一次时间

命令:ansible all -m cron -a 'name="custom job" minute=*/3 hour=* day=* month=* weekday=* job="/usr/sbin/ntpdate 172.16.254.139"'

group 模块:

目的:在所有节点上创建一个组名为nolinux,gid为2014的组

命令:ansible all -m group -a 'gid=2014 name=nolinux'

user 模块:

目的:在指定节点上创建一个用户名为nolinux,组为nolinux的用户

命令:ansible 10.1.1.113 -m user -a 'name=nolinux groups=nolinux state=present'

补充:删除用户示例
命令:<pre>ansible 10.1.1.113 -m user -a 'name=nolinux state=absent remove=yes'</pre>
yum 模块:

目的:在指定节点上安装 lrzsz 服务

命令:ansible all -m yum -a "state=present name=httpd"

service 模块:

目的:启动指定节点上的 puppet 服务,并让其开机自启动

命令:ansible 10.1.1.113 -m service -a 'name=puppet state=restarted enabled=yes'

script 模块:

目的:在指定节点上执行/root/a.sh脚本(该脚本是在ansible控制节点上的)

命令:ansible 10.1.1.113 -m script -a '/root/a.sh'

ping 模块:

目的:检查指定节点机器是否还能连通

命令:ansible 10.1.1.113 -m ping

command 模块:

目的:在指定节点上运行hostname命令

命令:ansible 10.1.1.113 -m command -a 'hostname'

raw 模块:

目的:在10.1.1.113节点上运行hostname命令

命令:ansible 10.1.1.113 -m raw-a 'hostname|tee'

get_url 模块:

目的:将http://10.1.1.116/favicon.ico文件下载到指定节点的/tmp目录下

命令:ansible 10.1.1.113 -m get_url -a 'url=http://10.1.1.116/favicon.ico dest=/tmp'

synchronize 模块:

目的:将主控方/root/a目录推送到指定节点的/tmp目录下

命令:ansible 10.1.1.113 -m synchronize -a 'src=/root/a dest=/tmp/ compress=yes'

执行效果:

delete=yes 使两边的内容一样(即以推送方为主)

compress=yes 开启压缩,默认为开启

--exclude=.Git 忽略同步. git 结尾的文件

由于模块,默认都是推送 push。因此,如果你在使用拉取 pull 功能的时候,可以参考如下来实现

mode=pull 更改推送模式为拉取模式

目的:将10.1.1.113节点的/tmp/a目录拉取到主控节点的/root目录下

命令:ansible 10.1.1.113 -m synchronize -a 'mode=pull src=/tmp/a dest=/root/'

由于模块默认启用了 archive 参数,该参数默认开启了 recursive, links, perms, times, owner,group 和 - D 参数。如果你将该参数设置为 no,那么你将停止很多参数,比如会导致如下目的递归失败,导致无法拉取

兼总条贯 知至知终

最后编辑于: April 2, 2018