一、Ansible简介与安装

Ansible是什么

1、用python编写的自动化运维工具,实现批量系统配置、批量程序部署、批量运行命令等功能。
2、基于各种模块实现不同功能
3、基于ssh通讯,不需要安装客户端
4、支持幂等性
5、2015年被红帽收购

什么是幂等性?
跟mysql中GTID的幂等性是一样的道理,判断目标主机有没有,有则跳过,没有则执行。
举例说明,使用ansible拷贝文件到远程主机,如果远程主机有该文件,ansible会对比两个文件的hash值,一致则不拷贝,不一致则覆盖。也是相当于判断文件是否一致,有没有,有则什么也不做,没有则执行。

工作原理


1、管理节点安装ansible,被管理节点开启ssh服务
2、管理节点将AdHocPlayBook转换为python脚本发给被管理端
3、被管理端执行python脚本并返回结果给管理节点

转换的python脚本临时存放在被管理端的/root/.ansible/tmp/目录下。

python版本要求

管理节点需要python>=2.6版本,Centos7默认为2.7版本
被管理节点需要python>=2.4版本

什么是AdHoc跟PlayBook
AdHoc相当于bash命令,一行命令看到结果
PlayBook相当于脚本,许多AdHoc的集合


在线安装

在管理主机上执行

$ yum install epel-release
$ yum install ansible

需要安装epel-release扩展源
配置ssh密钥认证

配置阿里镜像源

# pwd
$ cd /etc/yum.repos.d
$ cat aliBase.repo
[aliBase]
name=aliBase
baseurl=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/
enabled=1
gpgcheck=1
gpgkey=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/RPM-GPG-KEY-CentOS-$releasever
 
# cat aliEpel.repo
[aliEpel]
name=aliEpel
baseurl=https://mirrors.aliyun.com/epel/$releasever\Server/$basearch/
enabled=1
gpgcheck=0

$ yum install ansible

简单使用

1、使用Ping模块测试通信

$ vim /etc/ansible/hosts
10.154.0.112

#使用ping模块测试与10.154.0.112的通信
$ ansible 10.154.0.112 -m ping
10.154.0.112 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

$ ansible all -m ping
$ ansible all -i 10.154.0.112,10.154.0.113 -m ping
$ ansible all -i 10.154.0.112, -m ping
$ ansible all -i 10.154.0.112, -m copy -a "src=/tmp/test.txt dest=/tmp/test.txt"

注意-i参数在这里接收的是一个列表,如果只指定一个被管理节点时,需要在其后加上逗号
-i 参数指定ansible资产,即被管理服务器
-m 参数指定使用的模块
-a 参数指定模块的参数,如copy模块的src和dest参数

2、查看ansible版本

可以看到ansible配置文件位置,模块存放路径,python模块路径,ansible程序路径,python版本信息。


离线安装

ansible各个版本下载
待研究

参考资料:
B站课程:千锋教育ansible P1-4
朱老师博客
珂儿吖博客

posted @ 2021-04-24 20:25  努力吧阿团  阅读(156)  评论(0)    收藏  举报