Ansible运维自动化
一,工具与环境介绍
1.1 Ansible简介
- 批量管理服务器的工具。
- 优点:无需部署agent,没客户端,客户端只要支持Python即可。
- 通过ssh进行管理,远程登录管理。
- 目前github上最流行的自动化运维工具,没有之一。
1.2 Jenkins简介
- 可视化运维(主要用在可视化部署):能够把脚本或者管理工具的一些信息输出放在Web界面让你看,同时还可以看一些历史的信息输出。
- 可持续构建,和git,svn结合,可以发出指令把开发新写的代码从代码仓库里直接tar打包发送到对面服务器里同时启动自动安装程序。
git,svn:一种开发可以存放代码的仓库- 与ssh和ansible结合均可实现可视化运维
1.3 环境说明
- 关闭防火墙
- 关闭sekinux
二, Python3与Ansible的安装
2.1 使用源码安装Python3.5
2.1.1 安装支持包
装两个云yum源:
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repowget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
安装支持包:yum -y install lrzsz vim net-tools gcc gcc-c++ ncurses ncurses-devel unzip zlib-devel zlib openssl-devel openssl libffi-devel epel-release libselinux-python
2.1.2 源码包编译 Python3.5
云yum下载地址:
wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz
tar xf Python-3.5.2.tgz -C /usr/src/ cd /usr/src/Python-3.5.2/ ./configure --prefix=/usr/local/python 
make && make install 
2.1.2 做软连接
ln -s /usr/local/python/bin/python3 /usr/bin/python3
2.1.3 查版本号
python3 -V
2.2 使用pip3安装ansible
2.2.1 安装ansible最新版本
/usr/local/python/bin/pip3 install ansible
2.2.2 做软连接
ln -s /usr/local/python/bin/ansible /usr/local/bin which ansible ansible --version(查看版本号)
2.3 Ansible查看帮助
/usr/local/python/bin/ansible-doc -l 查看总帮助 /usr/local/python/bin/ansible-doc -s shell 查看Shell模块的帮助
三,使用公钥实现ssh无密码登陆
- 下载SCP
3.1 生成密钥对
ssh-keygen -t rsa -f ~/.ssh/id_rsa -P ""
``
3.2 分发密钥
sshpass -p 对方电脑登陆密码 ssh-copy-id -i ~/.ssh/id_dsa.pub "-o StrictHostKeyChecking=no 192.168.200.63"-o StrictHostKeyChecking=no 不记录
四,Ansible的简单配置和ping模块
4.1 Ansible的配置文件
通过pip3安装的ansible是没有配置文件的,需要我们自己创建一个
mkdir -p /etc/ansiblevim /etc/ansible/hosts
cat /etc/ansible/hosts[nginx] #被管理的主机组名称webA ansible_ssh_host=192.168.200.132 ansible_ssh_port=22 ansible_ssh_user=root #第一台主机webB ansible_ssh_host=192.168.200.138 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=666666 #第二台主机特别提示:WebA ===> 主机名ansible_ssh_host ===>主机IPansible_ssh_port ===>ssh的默认端口ansible_ssh_user ===>ssh的用户名ansible_ssh_pass ===>ssh的用户的连接密码
如果设置了ssh免密钥,就不需要写密码,例如:webA .没有设置免密钥,那么就需要安装sshpass工具,并在/etc/ansible/hosts文件里写上主机的连接密码。例如webB
下载epel源安装sshpass
2.[root@ansible python]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo3.[root@ansible python]# yum -y install sshpass4.[root@ansible python]# which sshpass5./usr/bin/sshpass
4.2 进行ansible远程执行命令测试
1.语法:
ansible Web1 -m command -a 'uptime'-->获取Web1服务器的平均负载值 ansible 主机组 -m ansible内置功能模块名 -a 命令
all:代表所有主机
nginx:模块名,只发nginx模块下的主机
单发:Web1=主机名
多发:Web1:Web2
指定all但不包含web2:all:\ !web1,注意!前需要加转意符号(\)
2.进行命令测试:
1.#进行ping模块的连接测试2.[root@ansible python]# ansible nginx -m ping3.webB | FAILED! => { #我们发现webB还是没链接成功,这是因为本机的known_hosts文件还没有记录对方主机的信息。4. "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this. Please add this host's fingerprint to your known_hosts file to manage this host."5.}6.webA | SUCCESS => { #webA成功7. "changed": false,8. "ping": "pong"9.}
4.3 ansible的简单使用方式
ansible -i /etc/ansible/hosts 主机或主机组 -m 指定模块 -a 命令 -i:指定配置文件位置,不指定默认去/etc/ansible/hosts 里找 -m : 指定操作模块,后跟模块名 -a :发布,后面跟命令
4.4 使用ping模块用来查看服务器是否连接正常,ping模块不需要-a指定参数
ansible all -m ping
操作测试
#A[root@ansible .ssh]# ansible webA -m pingwebA | SUCCESS => {"changed": false,"ping": "pong"}
# all[root@ansible .ssh]# ansible all -m pingwebA | SUCCESS => {"changed": false,"ping": "pong"}webB | SUCCESS => {"changed": false,"ping": "pong"}
#A:B[root@ansible .ssh]# ansible webA:webB -m pingwebA | SUCCESS => {"changed": false,"ping": "pong"}webB | SUCCESS => {"changed": false,"ping": "pong"}
#\!A[root@ansible .ssh]# ansible all:\!webA -m pingwebB | SUCCESS => {"changed": false,"ping": "pong"}
五,Ansible的三个命令模块
5.1 ansible模块command
1.command支持直接回显命令的执行结果
[root@ansible ~]# ansible all -m command -a "pwd"webA | SUCCESS | rc=0 >>/rootwebB | SUCCESS | rc=0 >>/root
注:command不支持管道符不支持重定向,不建议使用
5.2 Ansible模块shell
1.shell模块支持管道符
[root@ansible ~]# ansible all -m shell -a "echo testansible | grep a"webA | SUCCESS | rc=0 >>testansiblewebB | SUCCESS | rc=0 >>testansible
2.shell支持重定向
[root@ansible ~]# ansible all -m shell -a "echo bb >> /tmp/testansible"webA | SUCCESS | rc=0 >>webB | SUCCESS | rc=0 >>
注:如果遇到特殊符号需要加入\转义,ansible才能正常运行
5.3 Ansible模块raw,最原始的方式运行命令(不依赖python,仅通过ssh实现)
1.清除yum缓存
[root@ansible ~]# ansible all -m raw -a "yum -y clean all"webB | SUCCESS | rc=0 >>Loaded plugins: fastestmirrorCleaning repos: c7-mediaCleaning up everythingShared connection to 192.168.200.63 closed.webA | SUCCESS | rc=0 >>Loaded plugins: fastestmirrorCleaning repos: c7-media epelCleaning up everythingCleaning up list of fastest mirrorsShared connection to 192.168.200.132 closed.
4.建立yum缓存
[root@ansible ~]# ansible all -m raw -a "yum makecache"webA | SUCCESS | rc=0 >>Loaded plugins: fastestmirrorc7-media | 3.6 kB 00:00Loading mirror speeds from cached hostfile* c7-media:Metadata Cache CreatedShared connection to 192.168.200.132 closed.webB | SUCCESS | rc=0 >>Loaded plugins: fastestmirrorc7-media | 3.6 kB 00:00Loading mirror speeds from cached hostfile* c7-media:Metadata Cache CreatedShared connection to 192.168.200.138 closed.
3.yum装nmap包
ansible all -m raw -a "yum -y install nmap"
5.4Ansible的copy模块批量下发文件或文件夹
1. copy模块概述
**copy模块的参数:**ansible 主机组 -m 模块 -a 命令
osrc:指定源文件或目录
odest:指定目标服务器的文件或目录
obackup:是否要备份
oowner:拷贝到目标服务器后,文件或目录的所属用户
ogroup:拷贝到目标服务器后,文件或目录的所属群组
omode:文件或目录的权限
准备工作
[root@ansible ~]# mkdir -p /service/scripts[root@ansible ~]# echo "aaa" > /service/scripts/test.txt[root@ansible ~]# echo "bbb" > /service/scripts/test2.tx所有被管理端节点必须安装libselinux-python包yum -y install libselinux-python
2. copy模块拷贝文件
特别提示:如果目标路径不存在会自动创建 : src===>源文件路径 dest=目标路径位置
[root@ansible ~]# ansible all -m copy -a "src=/service/scripts/test.txt dest=/service/scripts/"webB | FAILED! => { #节点未安装libselinux-python"changed": false,"checksum": "972a1a11f19934401291cc99117ec614933374ce","msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"}webA | SUCCESS => {"changed": true,"checksum": "972a1a11f19934401291cc99117ec614933374ce","dest": "/service/scripts/test.txt","gid": 0,"group": "root","md5sum": "5c9597f3c8245907ea71a89d9d39d08e","mode": "0644","owner": "root","secontext": "system_u:object_r:svc_svc_t:s0","size": 4,"src": "/root/.ansible/tmp/ansible-tmp-1529035954.8010113-22928023490467/source","state": "file","uid": 0}
节点安装libselinux-python后在进行发送测试
[root@ansible ~]# ansible webB -m copy -a "src=/service/scripts/test.txt dest=/service/scripts/"webB | SUCCESS => { #发送成功"changed": true,"checksum": "972a1a11f19934401291cc99117ec614933374ce","dest": "/service/scripts/test.txt","gid": 0,"group": "root","md5sum": "5c9597f3c8245907ea71a89d9d39d08e","mode": "0644","owner": "root","secontext": "system_u:object_r:svc_svc_t:s0","size": 4,"src": "/root/.ansible/tmp/ansible-tmp-1529036146.1609693-94270890826089/source","state": "file","uid": 0}
3. copy模块拷贝文件夹
特别提示: 如果目标路径里有与我拷贝的文件同名文件的话,会直接覆盖目标路径下的文件
1.拷贝/service/scripts/ 目录下所有内容到dest的路径下
[root@ansible ~]# ansible webA -m copy -a "src=/service/scripts/ dest=/service/scripts/"webA | SUCCESS => {"changed": true,"dest": "/service/scripts/","src": "/service/scripts/"}
2.拷贝/service/scripts目录本身及其内部的所有内容到dest的路径下
[root@ansible ~]# ansible webA -m copy -a "src=/service/scripts dest=/service/scripts/"webA | SUCCESS => {"changed": true,"dest": "/service/scripts/","src": "/service/scripts"}
4 copy模块自动备份
特别提示:
参数:backup=yes ===>意思是,如果目标路径下,有与我同名但不同内容的文件时,在覆盖前,对目标文件先进行备份
[root@ansible ~]# ansible webB -m copy -a "src=/service/scripts/ dest=/service/scripts/ backup=yes"webB | SUCCESS => {"changed": true,"dest": "/service/scripts/","src": "/service/scripts/"}
5 copy模块指定用户和属主属组权限
[root@ansible ~]# ansible webA -m copy -a "src=/service/scripts/ dest=/service/scripts/ owner=nobody group=nobody mode=0600"webA | SUCCESS => {"changed": true,"dest": "/service/scripts/","src": "/service/scripts/"}
5.5 Ansible的script模块批量运行脚本
能够实现远程服务器批量运行本地的shell脚本
1.远程批量分发并自动部署nginx
所有被管理端需要挂载光盘,并创建本地yum配置文件
scripts目录下需要两个脚本和解压包:
1,自动分安装脚本
2,分发脚本
3.nginx-1.10.2.tar.gz #nginx源码包
1.自动安装脚本
#!/bin/sh#nginx install shell scriptstest -d /media/cdrom || mkdir -p /media/cdrom #有没有目录mount /dev/sr0 /media/cdrom &>/dev/null #挂在光盘yum -y install gcc gcc-c++ make pcre pcre-devel zlib zlib-devel openssl openssl-devel &>/dev/null #安装软件包test -d /service/scripts || mkdir -p /service/scripts #有没有目录没有创建cd /service/scripts/ #进入目录tar xf nginx-1.10.2.tar.gz -C /usr/src/ #解压包cd /usr/src/nginx-1.10.2/ #进入Nginx目录./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module &>/dev/null #编译make &>/dev/nullmake install &>/dev/null #安装exit 0
2.分发脚本
#!/bin/shGroup=$1 #对方服务器位置(主机名或主机组明)ansible $Group -m copy -a "src=/server/scripts/ dest=/service/scripts/ mode=0755" #分发范围ansible $Group -m script -a "/service/scripts/auto_nginx.sh" #远程激活
3.激活脚本
ansible web1:web2 -m script -a "/bin/sh /service/scripts/auto_nginx.sh"
六,Ansible-playbook的初步使用
playbook可以把ansible的模块进行组合
6.1 作软连接
ln -s /usr/local/python/bin/ansible-playbook /usr/local/bin/
6.2 playbook的简单shell模块的使用
1.playbook的执行模板**
--- #开头三个小-开头- hosts: webBtasks: #任务,标注- name: test #任务名字shell: echo "welcome to yunjisaun" >> /tmp/username #模块名:命令- name: test2shell: echo "welcome to yunjisuan" >> /tmp/username
模板说明:
--- #开头必须有三个小-,顶格写
- hosts: #正文配置代码的第一级,必须有两个空格(-占一个空格位)
- host: webB #webB是host参数的值,值和hosts:之间要有一个空格
tasks: #tasks:表示接下来要执行的具体任务
- name: #相对于tasks再多缩进两个格(-占一个空格位),表示属于tasks的下一级
- name: test #test只是要执行的具体命令的名字可以随便写。name:后还是有一个空格要注意
shell: #表示调用shell模块执行命令相对于tasks仍旧要多缩进两个空格
shell: echo "xxx" >> xxx #shell:后边还是要有个空格,需要注意。
2.激活剧本
ansible-playbook test_shell.yaml
6.3 playbook的简单copy模块的使用
1.做一个copy文件
ehco "welcome to yunjisuan" >> /tmp/test_copy
2.做剧本
vim test_copy.yaml---- hosts: alltasks:- name: test copycopy: src=/tmp/copy_test dest=/tmp/
3.剧本激活
ansible-playbook /service/scripts/test_copy.yaml
6.3 playbook使用register输出命令运行结果
我们在用playbook进行ansible模块操作的时候,并没有命令的执行结果输出,默认被隐藏了,可以通过register模块追加输出命令的执行结果
1.写剧本
---- hosts: alltasks:- name: test registershell: echo "welcome to yunjisuan"register: print_result #将之前命令的输出结果保存在变量print_result里- debug: var=print_result #将变量的值作为debug输出出来
2.执行剧本
ansible-playbook test_register.yaml
6.4 nginx配置下发并检测
1.写脚本
vim test_nginx_conf.yaml---- hosts: alltasks:- name: copy nginx.confcopy: src=/tmp/nginx.conf dest=/usr/local/nginx/conf/ backup=yes- name:shell: /usr/local/nginx/sbin/nginx -tregister: nginx_result- debug: var=nginx_result
2.执行脚本
ansible-playbook test_nginx_conf.yaml
七,playbook的自定义变量和内置变量
7.1 在Playbook中使用自定义变量
1.写剧本
---- hosts: allvars: #定义变量- name: "yunjisuan" #第一个name变量age: "3" #第二个age变量tasks:- name: "{{ name }}" #{{}}两对大括号引用变量,变量名两头空格shell: echo "myname {{ name }},myage {{ age }}"register: var_result- debug: var=var_result特别提示:引用变量需要在双引号中引用
注:会有一个警告:因为自定义变量的名字和自定义变量名字冲突[WARNING]: Found variable using reserved name: name
把name修改为Name即可
2.执行剧本
ansible-playbook /service/scripts/test_vars.yaml
7.2 在playbook中使用ansible内置变量
查看内置变量:ansible 127.0.01 -m setup | less 
1. 写剧本
vim est_setupvars.yaml---- hosts: allgather_facts: True #使用ansible内置变量tasks:- name: setup varshell: echo "ip {{ ansible_all_ipv4_addresses[0] }} cpu {{ ansible_processor_count }}"register: var_result- debug: var=var_result
2. 执行脚本
ansible-playbook test_setupvars.yaml
八,Playbook下发可变配置文件
8.1 利用template模块下发可变的配置文件
1.写一个含有变量的文件
vim /tmp/testmy name is {{ myname }} #自定义变量my name is {{ ansible_all_ipv4_addresses[0] }} #系统变量
2.写一个文件的含有变量
vim test_filevars.yaml---- hosts: allgather_facts: True #开启系统变量vars:- myname: "yunjisuan" #自定义变量tasks:- name: template testtemplate: src=/tmp/test dest=/root/test #使用template下发可变配置文件
执行剧本
ansible-playbook test_filevars.yaml
8.2 下发配置文件里面使用判断语法
1.写一个半段语法的文件,以.j2结尾
vim /tmp/if.j2{% if PORT %} #if PORT存在ip=0.0.0.0:{{ PORT }}{% else %} #不为真ip=0.0.0.0:80{% endif %} #结尾
测试:
vim test_ifvars.yaml ---- hosts: allgather_facts: True #开启系统内置变量vars:- PORT: 90 #自定义变量tasks:- name: jinja2 if testtemplate: src=/tmp/if.j2 dest=/root/test
2.执行剧本
九, Playbook的notify通知和下发nginx配置
1.实战下发可执行动作的可变的nginx配置文件
# cat test_nginxvars.yaml---- hosts: allgather_facts: True #开启系统内置变量tasks:- name: nginx conftemplate: src=/tmp/nginx.j2 dest=/usr/local/nginx/conf/nginx.confnotify:- reload nginx #下发通知给handlers模块执行名字叫做reload nginx的动作handlers: #定义动作- name: reload nginx #动作的名字shell: /usr/local/nginx/sbin/nginx -s reload
2.执行剧本
ansible-playbook test_nginxvars.yaml
注:当你的上一条使得对方发生了改变才会触发notify通知
对新装的操作系统部署服务:
1.自动安装服务
2.把写好的配置文件覆盖到远程主机服务目录下
3.启动服务
已经部署好的服务,更新配置文件
1.Nginx反向代理引流(发个配置文件重启服务)
搭建LNMP步骤模块划分
1.搭建Nginx
2.搭建PHP
3.搭建MySQL
4.分发Nginx,php,MySQL的配置文件
4.启动nginx,php,mysql

浙公网安备 33010602011771号