什么是Ansible:

ansible是新出现的自动化运维工具,基于Python开发,
集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,
实现了批量系统配置、批量程序部署、批量运行命令等功能。

工作方式

ansible是基于模块工作的,本身没有批量部署的能力。
真正具有批量部署的是ansible所运行的模块,ansible只是提供一种框架。

主要包括:

(1)、连接插件connection plugins:负责和被监控端实现通信;
(2)、host inventory:指定操作的主机,是一个配置文件里面定义监控的主机;
(3)、各种模块核心模块、command模块、自定义模块;
(4)、借助于插件完成记录日志邮件等功能;
(5)、playbook:剧本执行多个任务时,非必需可以让节点一次性运行多个任务。

优势:

1、部署简单,只需要在主控端部署Ansible环境,被控制端无需任何操作。
2、默认使用SSH协议对设备进行管理
3、主从集中化管理
4、配置简单、功能强大、扩展性强
5、支持API及自定义模块,可通过Python轻松扩展
6、通过Playbooks来制定强大的配置。状态管理
7、对云计算平台、大数据都有很好的支持
8、提供一个功能强大、操作性强的Web管理界面和REST API接口——AWX平台
9、幂等性:一种操作重复多次结果相同

ansible的安装和测试

前提需要每台机器都能相互登录,配置好SSH
1、epel 源配置
2、sudo yum -y install epel-release
3、yum -y install ansible
4、ansible配置
5、在ansible的配置文件中添加主机信息,即可与目标主机进行通信,
配置文件位置/etc/ansible/hosts,其中,[web][test]为主机组,
可以批量控制主机组里面的所有主机,一个主机可以添加到多个组
6、/etc/ansible/hosts     #将以下IP添加到文件尾部
[web]
192.168.15.51
192.168.15.53
[test]
192.168.15.53
192.168.15.55
[severall]
192.168.15.51
192.168.15.53
192.168.15.55

ansible test --list
ansible web --list
ansible serverall --list
ansible all -m ping     #检查所有IP是否能ping通

ansible的模块使用

1、远程命令模块
command:默认的模块,可以运行远程权限范围所有的shell命令
script:在远处主机上执行主控制端存储的shell脚本文件,相当于scp+shell组合
shell:执行远程主机的shell监本文件
ansible web -m command -a "free -m"   #查看内存说明
ansible web -m command -a "df -h"     #查看磁盘使用情况

示例:
编写一个脚本:
vim hello.sh
#!/bin/bash
echo "1234"
测试:
[root@localhost test]# sh hello.sh 
1234

ansible web -m script -a "/root/test/hello.sh"
ansible web -m shell -a "/root/test/hello.sh"

2、copy模型

实现主控制端向目标拷贝文件,类似于scp
ansible web -m copy -a "src=/etc/fstab dest=/tmp/ owner=root group=root mode=744"

3、stat模块

获取远程文件状态信息,如:atime,md5,uid等
ansible web -m stat -a "path=/etc/hosts"

4、get_url模块

实现远程主机下载指定的URL到本地,支持sha256sum校验和
ansible web -m get_url -a "url=https://www.baidu.com/,dest=/tmp/index.html mod=440 force=yes"

5、yum模块

Linux平台软件包管理平台管理模块
ansible web -m yum -a "name=curl state=latest"

6、cron模块

远程主机的计划任务配置
ansible web -m cron -a 'minute=* weekday=2,4,6 job='/usr/bin/wall FBI WARNING' name=warningcron'
#取消
ansible all -m cron -a "name=warningcron state=absent"
#禁用
ansible all -m cron -a'disable=true job="/usr/bin/wall FBI Warning"name=warningcron'
#启用
ansible all -m cron -a 'disable=false job="/usr/bin/wall FBI WARNING" name=warningcron'
#
****2,4,6

7、mount模块

远程主机挂载
ansible web -m mount -a "name=/mnt/data dest=/dev/sda1 fstpe=ext4 opts=ro state=present"

8、service模块

远程主机系统服务管理
ansible web -m service -a "name=httpd state=restarted"

查看模块的方法

ansible-doc -l
ansible-doc fetch
ansible-doc -s fetch