Ansible 基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优势,实现了批量系统配置、批量程序部署、批量运行命令等功能。ansible是基于模块工做的,自己没有批量部署的能力。真正具备批量部署的是ansible所运行的模块,ansible只是提供一种框架。shell
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo数据库
下载阿里yum源vim
而后,清除yum缓存,并生成新的yum缓存元数据。缓存
yum clean all服务器
yum makecache fast网络
而后,用yum下载ansible软件多线程
yum -y install ansible --downloadonly --downloaddir=/ansible7框架
ls /ansible7运维
createrepo /ansible7 (必作)生成yum的repodata仓库数据库(metadata元数据)文件夹和文件ssh
建立ansible7的yum配置文件
vim /etc/yum.repo.d/ansible7.repo
[ansible7]
name=asible 7
baseurl=file:///ansible7
enable=1
gpgcheck=0
删除网络yum源配置文件
cd /etc/yum.repo.d
rm -rfv C*.repo epel.repo
yum clean all
yum repolist
yum search ansible
yum -y install ansible
http://mirrors.aliyun.com/repo/epel-7.repo
for i in {1..5}
do
(ssh root@192.168.11.$i ‘yum -y install vsftpd ftp lftp’)& 多线程
done
安装ansible软件
先下载ansible包
yum -y install ansible
rpm -qc ansible
vim /etc/ansible/hosts 在最后添加以下内容
[qf]
192.168.11.11
192.168.11.12
生成秘钥对,并上传公钥给要管理的主机
ssh-keygen
ssh-copy-id root@192.168.11.11
ssh-copy-id root@192.168.11.12
测试ansible的使用
语法:ansible 主机名或ip -m 模块名 -a ‘模块的选项和参数’
ansible选项:
-m 指定模块,常见的模块有ping ,shell,command,cron,user,group,yum等
-a 指定模块的选项参数,参数中state状态有present(如今就有,用于建立)、absent(缺席的,用于删除)两种
eg:ansible 192.168.11.12 -m shell -a ‘ip a’
用ansible给qf主机组中的全部主机新增jack用户。而后删除jack用户。
ansible qf -m user -a “name=’jack’ shell=’/sbin/nologin’ state=’present’”
ansible qf -m shell -a ‘id jack;tail -5 /etc/passwd’
新增jack用户
ansible qf -m user -a “name=’jack’ remove=yes state=’absent’”
ansible qf -m shell -a ‘id jack;tail -5 /etc/passwd’
setup:查看远程主机的基本信息 例:ansible qf -m setup
ping: ansible qf -m ping 测试远程主机的运行状态
file: ansible qf -m file -a “path=’/aa/bb’ state=’directory’”设置文件属性
force:须要在两种状况下强制建立软连接,一种是源文件不存在,但以后会创建的状况下;另外一种是目标软连接已存在,须要先取消以前的连接,而后创造新的软连接,有2个选项:yes|no
group:定义文件/目录的属组
mode:定义文件/目录的权限
owner:定义文件/目录的属主
path:必选项,定义文件/目录的路径
recurse:递归设置文件的属性,只对目录有效,有两个选项:yes|no
src:被连接的源文件路径,只应用于state=link的状况
state:
directory:若是目录不存在,就建立目录
file:即便文件不存在,也不会被建立
link:建立软连接
hard:建立硬连接
touch:若是文件不存在,则会建立一个新的文件,若是文件或目录已存在,则更新其最后修改时间
absent:删除文件
expect
shell脚本须要交互式的地方,有些命令须要手动去交互如passwd scp
对自动部署免去用户交互的痛苦,expect能很好的解决这类问题
expect 把交互式操做变成非交互式
expect的核心spawn expect send set
spawn 调用要执行的命令
expect 等待命令提示信息的出现,也就是捕捉用户输入的提示
send 发送须要交互的值,代替了用户手动输入的内容
set 设置变量值
set timeout 300 300秒超时 若是300秒没有expect内容出现就退出
设置expect永不超时
set timeout -1
interact 执行完成后保持交互状态。若是没有这一句登录完成后会退出
expect eof 这个必定要加,与spawn对应表示捕获终端输出信息终止,相似于if ...then ...fi
expect脚本必须以interact或expect eof结束,执行自动化任务一般expect eof就够了。
expect使用实例:
1.首先确认expect的包是否安装
#rpm -qa | grep expect
#yum install -y expect
2.安装完成后查看expect的路径,能够用
which expect
/usr/bin/expect
例:制做秘钥并将公钥发给ssh服务器192.168.11.12,其密码是0
vim a.txt
运行脚本
chmod -v +x a.txt
. a.txt
查看公钥和私钥
这样就成功了。
如需给多台服务器发送公钥只需写一个for循环就够了。