天天看点

ansible

究竟要不要自动化?

首先确认批量管理我们需要什么:无外乎主机分组管理、实时批量执行命令或脚本、实时批量分发文件或目录、定时同步文件等。

ansible由于走的是ssh,所以它有认证的过程,以及加密码的过程,这使得ansible非常慢,不适用于大规模环境(指上千台)。

4. 匹配目标

ansible <pattern_goes_here> -m <module_name> -a <arguments>

ansible  qing   -m service -a "name=httpd state=restart"

<pattern_goes_here> 参数的用法

192.168.4.34 或www.qing.com  匹配目标地址或主机名,多个ip或主机名使用‘:’号分隔

qing                         匹配目标组为qing, 多个组使用用":" 分隔

all 或 "*"                   匹配目标所有主机

~(web|db).*\.example\.com 或 192.168.1.*   支持正则表达式匹配主机或ip地址

qing:!192.168.4.34         匹配目标组qing 但是配置192.168.4.34的主机ip

qing:&ming                  匹配qing和ming 两个群组的交集

qing:!`excluded`:&`required`  支持变量匹配方式

5. ansible 常用模块及api

0. 默认模块名为command 所以 -m command 可以省略  例: ansible qing -a 'ls /tmp'

1. ansible qing -m ping   检测主机状态

2. 模块默认存储目录:/usr/share/ansible/

3. ansible-doc command  可以查看模块使用帮助

4. 常用模块介绍:

   1. 远程命令模块

      1.1 功能  command 作为ansible的默认模块,可以运行远程权限范围内的所有shell命令   ansible qing -m command -a 'free -m'

                script 功能是在远程主机执行主控端存储的shell脚本文件,相当于scp+shell 组合   ansible qing -m script -a '/tmp/qing.sh'

                shell  执行远程主机的shell脚本文件    ansible qing -m shell -a '/tmp/ming.sh' 

   2. copy模块

      ansible qing -m copy -a 'src=/tmp/fanqing.txt dest=/qing/ owner=root group=root mode=0755'

      copy 控制主机下/tmp/fanqing.txt 到目标主机/qing/下 并改变用户、组、权限

   3. state模块

      ansible qing -m stat -a 'path=/qing/fanqing.txt'

      获取文件状态信息

   4. get_url模块

      ansible qing -m get_url -a 'url=http://www.baidu.com dest=/qing/index.html mode=0440 force=yes'

   5. yum模块

      ansible 192.168.4.34 -m yum -a 'name=httpd state=latest'

      yum安装软件包

   6. cron模块

      ansible 192.168.4.34 -m cron -a "name='check dirs' hour='5,2' job='ls -alh > /dev/null'"

      结果:#ansible: check dirs

             * 5,2 * * * ls -alh > /dev/null 

   7. mount

     ansible 192.168.4.34 -m mount -a 'name=/mnt/data src=/dev/sd0 fstype=ext3 opts=ro state=present'

   8. service 模块

      ansible qing -m service -a 'name=httpd state=started'

      state参数:started,stopped,restarted,reloaded

   9. user模块

      ansible qing -m service -a 'name=qing shell=/bin/bash groups=admins,developers append=yes'

6. playbook

handlers

tasks

templates

继续阅读