搜索
您的当前位置:首页正文

ansible module

来源:二三娱乐
  • 入门
    首先把ssh密钥搞好,这里就不说了,保证master和minion之间不通过密码
    定义主机和组:
    vim /etc/ansible/hosts #默认的文件位置,也可执行ansible时手动指定hosts文件,通过-i参数
[test]
10.199.2.45
10.199.2.46
[web]
10.199.2.[42:47]  #=10.199.2.42\43\44\45\46\47
  #主机名定义

ping模块

ansible test -m ping -u sre -s       #-m接模块名,因为我们使用的是sre账户登录后通过sudo的方式,-u接用户,-s表示sudo方式执行
ansible test:\!10.199.2.46 -m ping -u sre -s       #:\!排除某个主机
ansible 10.199.2.46 -m ping -u sre -s       #当然也可以直接接ip而不使用组进行

ansible自带了很多模块
可以通过ansible-doc -l 查看总共有哪些模块,ansible-doc ping 显示某个模块的用法,ansible-doc -s ping 显示某个模块在playbooks中的代码片段
远程执行命令模块:
远程执行命令可能是ansible最常用也是最方便的一个功能,这里举几个例子
command模块

ansible test -a 'w' -u sre -s     #默认模块command,实现执行远程命令,-a接模块参数

script模块
master先创建脚本1.sh

#!/bin/bash
ls /tmp/
ansible test -m script -a '1.sh' -u sre -s         #script模块相当于scp+shell,将本地脚本在远端minion进行执行

shell模块
shell和command模块很类似,看帮助信息了解到command和shell功能基本一致,但shell可以使用环境变量、管道等,功能更强大

ansible -s agent -m shell -a 'sudo su - game -c "/bin/sh /export/install/scripts/zabbix/zabbix.sh 'enable'"'

**copy模块 **

ansible test -m copy -a 'src=1.sh dest=/tmp/ owner=root group=root mode=0755' -u sre -s    #将本地1.sh文件传到远端,如第二次执行此命令,如无更新,则远端无更新,有更新,则远端更新

yum模块

ansible test -m yum -a "name=nc state=latest" -u sre -s

cron模块

ansible test -m cron -a "name='test' job='ls /tmp' minute=*/2 hour=3,4,5" -u sre -s
#Ansible: test        #在agent上执行命令crontab -l查看
*/2 3,4,5 * * * ls /tmp
ansible test -m cron -a "name='test' state=absent" -u sre -s #删除该条cron

service模块

ansible test -m service -a "name=ntpd state=started" -u sre -s      #启动ntpd服务
ansible test -m service -a "name=ntpd state=stopped" -u sre -s    #停止ntpd服务

user模块

ansible test -m user -a "name=test123" -u sre -s         #创建用户
ansible test -m user -a "name=test123 state=absent remove=yes" -u sre -s     #删除用户并删除家目录

lineinfile模块

用于文件内的内容处理
ansible ctx-lf -m lineinfile -a "dest=/tmp/sudoers line='appuser  ALL=(ALL)       NOPASSWD:ALL' insertafter=^sre" -u sre -s -i host  #在sudo文件中sre开头之后加入line=的内容,insertafter可以写正则或EOF(结尾),同理还有insertbefore也可以写正则或BOF(开头)
ansible ctx-lf -m lineinfile -a "dest=/tmp/sudoers state=absent regexp=^appuser" -u sre -s -i hosts  #去掉正则匹配的所有行
ansible ctx-lf -m lineinfile -a "dest=/tmp/sudoers regexp=^sre line='#sre  ALL=(ALL)       NOPASSWD:ALL'" -u sre -s -i hosts  #将sre开头的最后匹配的一行前边加上#
也可以用()形式做替代变更,类似sed
ansible ctx-lf -m lineinfile -a "dest=/tmp/sudoers regexp=^(sre.*)$ line='#\1' backrefs=yes" -u sre -s -i hosts   \1表示第一个()里的内容,注意这种用法需要backrefs为yes,开启扩展正则匹配
ansible ctx-lf -m lineinfile -a "dest=/tmp/sudoers regexp=^(sre.*)$ line='123123' validate='visudo -cf %s'" -u sre -s -i hosts   #加入validate的验证,比如sudo文件如果改错了,可能影响整个系统的管理,加入验证之后,如果修改的sudo文件格式错误,将不会保存

lineinfile模块栗子:在指定行后添加

addline.jpg

lineinfile模块栗子:文件末尾添加

endline.jpg
Top