Ansible自动化运维实战:从入门到精通,轻松管理服务器集群 Ansible自动化运维实战从入门到精通轻松管理服务器集群简介核心组件基本操作常用模块实践Shell模块复制模块用户模块软件包管理服务模块文件模块收集模块编写任务剧本简介Ansible是基于Python语言开发的Ansible由EPEL仓库提供Ansible是一款能够批量执行远程操作系统指令的自动化运维工具Ansible采用无客户端架构。核心组件核心模块主机清单Inventory任务剧本Playbook基本操作密钥认证# 生成密钥默认生成到~/.ssh路径下密码设置为空否则后续ansible命令都要再手工输入ssh-keygen-f ~/.ssh/id_rsa-P# 推送公钥到目标主机默认用户为rootssh-copy-id用户名IP地址当客户机较多时而连接密码一致可以通过Shell自动化脚本提升操作效率#!/bin/bash# 配置参数IP_LIST192.168.1.2 192.168.1.3USERNAMErootPASSWORD123456forip in$IP_LISTdosshpass-p$PASSWORDssh-copy-id-i ~/.ssh/id_rsa.pub-o StrictHostKeyCheckingno$USERNAME$ipdone部署Ansibleyum install-y epel-release yum clean all yum makecache yum install-y ansible ansible--version编写主机清单修改/etc/ansible/hosts文件使用中括号设置组名记录对应的主机名或主机IP地址也能配置主机对应的连接用户和密码配置主机非默认端口如果连接的用户和密码一致也可以通过组变量配置。如果已对目标客户机做了密钥认证则对应配置了ansible_ssh_pass不起效果客户机直接通过公钥认证了。[web1]host1 192.168.1.2[web2]host2 192.168.1.3 host[3:5]ansible_ssh_userrootansible_ssh_pass123456ansible_ssh_port2222[webserver:children]web1 web2[webserver:vars]ansible_ssh_userrootansible_ssh_pass12345678测试# -o简洁输出ping非测试网络ICMP协议而是SSH连通性ansible web1-m ping-o测试的主机组名或IP地址需要在/etc/ansible/hosts文件中被找到否则被忽略当测试连接不通时可以通过客户机的/var/log/secure日志排查。常用模块实践Shell模块# -f指定并发进程数默认是5ansible webserver-m shell-ahostname-o-f 2复制模块# 将/etc目录下的hosts文件复制到目标主机/tmp目录下并命名为1.txt如果目标文件名存在则进行备份备份命名为1.txt.时间戳~默认是不进行备份ansible webserver-mcopy-asrc/etc/hosts dest/tmp/1.txt ownerroot groupbin mode777 backupyes用户模块# 创建用户ansible webserver-m user-anamelisi statepresent# 修改密码ansible webserver-m user-anamelisi password$(echo12345678|openssl passwd-1-stdin)# 修改shellansible webserver-m user-anamelisi shell/sbin/nologin# 删除用户ansible webserver-m user-anamelisi stateabsent# 给用户添加组默认append为no则原来用户已经存在的附加组被移除ansible webserver-m user-anamelist groupsdocker,nginx appendyes软件包管理# 升级所有包ansible host1-m yum-aname* statelatest# 安装apacheansible host2-m yum-anamehttpd statelatest# 卸载apacheansible host2-m yum-anamehttpd stateremoved服务模块# state状态有started,stopped,restarted,开机自启enabled有yes,noansible host2-m service-anamehttpd statestarted enabledyes文件模块# 创建文件ansible host1-m file-apath/tmp/1.txt mode777 statetouch# 创建目录ansible host1-m file-apath/tmp/2 mode777 statedirectory收集模块# 查询所有信息ansible host2-m setup# 过滤查询IP地址ansible host2-m setup-afilteransible_all_ipv4_addresses编写任务剧本任务剧本是将安装软件、复制配置、服务启动等一系列过程组织串到一起以键值对格式存在文件内容中的。Handlers是特殊任务存在以下特点在所有tasks执行完毕后运行只有被notify指令通知时才执行去重执行即使被多次notify最多只执行一次----name:Install Apache Web Serverhosts:web1tasks:-name:Ensure Apache is at the latest versionyum:name:httpdstate:latestnotify:-restart apache-name:Copy Apache confcopy:src./httpd.conf dest/etc/httpd/conf/httpd.conf-name:Ensure Apache service is enabledservice:name:httpdstate:startedenabled:yeshandlers:-name:restart apacheservice:name:httpdstate:restarted实施任务剧本常用命令# 检验语法ansible-playbook apache.yaml--syntax-check# 列出任务ansible-playbook apache.yaml--list-tasks# 列出主机ansible-playbook apache.yaml--list-hosts# 执行ansible-playbook apache.yaml