linux_7
一、 ansible的功能
批量执行远程命令,可以对远程的多台主机同时进行命令的执行
批量安装和配置软件服务,可以对远程的多台主机进行自动化的方式配置和管理各种服务
编排高级的企业级复杂的IT架构任务,Ansible的Playbook和role可以轻松实现大型的IT复杂架构
提供自动化运维工具的开发API,有很多运维工具,如jumpserver就是基于 ansible 实现自动化管理功能
二、 ansible的特性
模块化:调用特定的模块完成特定任务,支持自定义模块,可使用任何编程语言写模块
Paramiko(python对ssh的实现),PyYAML,Jinja2(模板语言)三个关键模块
基于Python语言实现
部署简单,基于python和SSH(默认已安装),agentless,无需代理不依赖PKI(无需ssl)
安全,基于OpenSSH
幂等性:一个任务执行1遍和执行n遍效果一样,不因重复执行带来意外情况,此特性非绝对
支持playbook编排任务,YAML格式,编排任务,支持丰富的数据结构
较强大的多层解决方案 role
三、 ansible的安装配置
关闭防火墙:systemctl disable –now firewalld
系统版本 CentOS 7.9
服务器 10.0.0.131(主机名:centos7-01)
客户端 10.0.0.132(主机名:centos7-02)
客户端 10.0.0.133(主机名:centos7-03)
客户端 10.0.0.134(主机名:centos7-04)
#1、CentOS 7.9 rpm包安装ansible
[root@centos7-01 ~]# yum install -y ansible
#2、版本信息
[root@centos7-01 ~]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Oct 14 2020, 14:45:30) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
#3、使用工具前需先配置ansible主控端能基于密钥认证,先修改下面一行,实现首次登录不显示询问提示
[root@centos7-01 ~]# vim /etc/ssh/ssh_config
# StrictHostKeyChecking ask 改为 StrictHostKeyChecking no
#4、检查对应服务器的host_key,建议取消此行注释,实现第一次连接自动信任目标主机
[root@centos7-01 ~]# vim /etc/ansible/ansible.cfg
host_key_checking = False
#5、可用脚本实现基于key验证
[root@centos7-01 ~]# vim ssh_key.sh
#!/bin/bash
#密码
PASS=a123456
#设置网段最后的地址,4-255之间,越小扫描越快,可根据实际情况修改
END=254
IP=`ip a s eth0 | awk -F'[ /]+' 'NR==3{print $3}'`
NET=${IP%.*}.
rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
for((i=3;i<="$END";i++));do
ping -c 1 -w 1 ${NET}$i &> /dev/null && echo "${NET}$i" >> SCANIP.log &
done
wait
ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass || yum -y install sshpass
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP
AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done
#把.ssh/known_hosts拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/
done
#6、运行脚本实现基于key验证
[root@centos7-01 ~]# bash ssh_key.sh
Generating public/private rsa key pair.
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Rj9PiTavsJMg8YPHJqpDDGZmAPDifl5LCsMEAORb0Iw root@centos7-01
The key's randomart image is:
+---[RSA 2048]----+
|Xo+ |
|+E.o |
|+... . |
|+*o . . . . . |
|B+ = S * o |
|+o + B. . * |
|.= o B o.. o |
|. * + . oo . |
|.o o . ... |
+----[SHA256]-----+
sshpass-1.06-1.el7.x86_64
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -o 'StrictHostKeyChecking=no' '10.0.0.128'"
and check to make sure that only the key(s) you wanted were added.
Warning: Permanently added '10.0.0.131' (ECDSA) to the list of known hosts.
Warning: Permanently added '10.0.0.132' (ECDSA) to the list of known hosts.
Warning: Permanently added '10.0.0.134' (ECDSA) to the list of known hosts.
Warning: Permanently added '10.0.0.133' (ECDSA) to the list of known hosts.
known_hosts 100% 1032 717.2KB/s 00:00
known_hosts 100% 1032 1.3MB/s 00:00
known_hosts 100% 1032 722.3KB/s 00:00
known_hosts 100% 1032 574.9KB/s 00:00
known_hosts 100% 1032 288.0KB/s 00:00
#7、主机清单配置,目前演示环境有1台服务器、3台客户端
[root@centos7-01 ~]# vim /etc/ansible/hosts
[local]
10.0.0.131 ansible_connection=ssh
[webservers]
10.0.0.132
10.0.0.133
[dbservers]
10.0.0.131
10.0.0.132
[appservers]
10.0.0.133
10.0.0.134
#8、验证连通性
[root@centos7-01 ~]# ansible all -m ping
10.0.0.132 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.0.0.131 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.0.0.133 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
10.0.0.134 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
四、 ansible的帮助
#ansible-doc,此工具用来显示模块帮助,相当于man
格式:
ansible-doc [options] [module...]
-l, --list #列出可用模块
-s, --snippet #显示指定模块的playbook片段
#查看帮助
ansible --help
man ansible
ansible-doc --help
#列出所有模块
ansible-doc -l
#查看指定模块帮助用法
ansible-doc ping
#查看指定模块帮助用法,显示指定模块的playbook代码段
ansible-doc -s ping
5.1、Command 模块
功能:在远程主机执行命令,此为默认模块,可忽略 -m 选项
注意:此命令不支持 $VARNAME < > | ; & 等,可用shell模块实现,此模块不具有幂等性
#1、webservers组的IP地址
ansible webservers -m command -a 'hostname -I'
[root@centos7-01 ~]# ansible webservers -m command -a 'hostname -I'
10.0.0.133 | CHANGED | rc=0 >>
10.0.0.133
10.0.0.132 | CHANGED | rc=0 >>
10.0.0.132
#2、webservers组创建文件
[root@centos7-01 ~]# ansible webservers -m command -a 'touch /data/ansible.log'
[root@centos7-01 ~]# ansible webservers -m command -a 'touch /ansible.log'
[WARNING]: Consider using the file module with state=touch rather than running 'touch'. If you need to use command because file is insufficient you can add 'warn: false' to this command
task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
10.0.0.133 | CHANGED | rc=0 >>
10.0.0.132 | CHANGED | rc=0 >>
[root@centos7-01 ~]# ansible webservers -m command -a 'ls -l /ansible.log'
10.0.0.132 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 May 22 22:47 /ansible.log
10.0.0.133 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 0 May 22 22:47 /ansible.log
#3、webservers组创建文件夹
[root@centos7-01 ~]# ansible webservers -m command -a 'creates=/data/mysql mkdir -pv /data/mysql'
[WARNING]: Consider using the file module with state=directory rather than running 'mkdir'. If you need to use command because file is insufficient you can add 'warn: false' to this
command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
10.0.0.133 | CHANGED | rc=0 >>
mkdir: created directory ‘/data’
mkdir: created directory ‘/data/mysql’
10.0.0.132 | CHANGED | rc=0 >>
mkdir: created directory ‘/data’
mkdir: created directory ‘/data/mysql’
[root@centos7-01 ~]# ansible webservers -m command -a 'ls -l /data/'
10.0.0.132 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 May 22 22:49 mysql
10.0.0.133 | CHANGED | rc=0 >>
total 0
drwxr-xr-x 2 root root 6 May 22 22:49 mysql
5.2、shell 模块
注意:此模块不具有幂等性
[root@centos7-01 ~]# ansible webservers -m shell -a 'echo hello > /data/hello.log'
10.0.0.133 | CHANGED | rc=0 >>
10.0.0.132 | CHANGED | rc=0 >>
[root@centos7-01 ~]# ansible webservers -m shell -a 'cat /data/hello.log'
10.0.0.132 | CHANGED | rc=0 >>
hello
10.0.0.133 | CHANGED | rc=0 >>
hello
功能:在远程主机上运行ansible服务器上的脚本(无需执行权限)
注意:此模块不具有幂等性
#1、webservers组创建文件并写入内容hello
[root@centos7-01 ~]# ansible webservers -m shell -a 'echo hello > /data/hello.log'
10.0.0.132 | CHANGED | rc=0 >>
10.0.0.133 | CHANGED | rc=0 >>
[root@centos7-01 ~]# ansible webservers -m shell -a 'ls -l /data/hello.log'
10.0.0.132 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 6 May 22 22:54 /data/hello.log
10.0.0.133 | CHANGED | rc=0 >>
-rw-r--r-- 1 root root 6 May 22 22:54 /data/hello.log
[root@centos7-01 ~]# chmod +x test.sh
[root@centos7-01 ~]# ansible webservers -m script -a '/root/test.sh'
10.0.0.132 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 10.0.0.132 closed.\r\n",
"stderr_lines": [
"Shared connection to 10.0.0.132 closed."
],
"stdout": "10.0.0.132 \r\n",
"stdout_lines": [
"10.0.0.132 "
]
}
10.0.0.133 | CHANGED => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 10.0.0.133 closed.\r\n",
"stderr_lines": [
"Shared connection to 10.0.0.133 closed."
],
"stdout": "10.0.0.133 \r\n",
"stdout_lines": [
"10.0.0.133 "
]
}
功能:从ansible服务器主控端复制文件到远程主机
注意: src=file 如果是没指明路径,则为当前目录或当前目录下的files目录下的file文件
#如目标存在,默认覆盖,此处指定先备份
[root@centos7-01 ~]# ansible webservers -m copy -a 'src=ssh_key.sh dest=/data/ssh.sh owner=chen group=bin mode=700'
[root@centos7-02 data]# ll
total 8
-rw-r--r-- 1 root root 6 May 23 20:43 hello.log
drwxr-xr-x 2 root root 6 May 22 22:49 mysql
-rw-r--r-- 1 root root 826 May 23 20:47 ssh.sh
#复制/etc目录自身,注意/etc/后面没有/,ansible拷贝文件夹比较慢
[root@centos7-01 ~]# ansible webservers -m copy -a "src=/etc dest=/data/"
#复制/etc/下的文件,不包括/etc/目录自身,注意/etc/后面有/
[root@centos7-01 ~]# ansible webservers -m copy -a "src=/etc/ dest=/data/"
[root@centos7-02 ~]# ls /data/
at.deny fuse.conf machine-id named.conf passwd- shadow system-release-cpe
autofs.conf group- mailcap named.rfc1912.zones profile shadow- vimrc
centos-release inittab man_db.conf netconfig rwtab statetab yum.conf
cron.deny locale.conf mime.types os-release sestatus.conf system-release
5.5、Fetch 模块
从远程主机提取文件至ansible的主控端,该模块的工作原理与[copy]类似,但与之相反,它用于从远程机器获取文件,并将它们存储在本地文件树中,按主机名组织,目前不支持目录
[root@centos7-01 ~]# ansible webservers -m fetch -a 'src=/var/log/messages dest=/data/log'
[root@centos7-01 ~]# ll /data/
total 4
drwxr-xr-x 4 root root 42 May 23 20:55 log
drwxr-xr-x 6 mysql mysql 4096 May 23 20:29 mysql
5.6、File 模块
设置文件属性,创建软链接
#创建空文件
[root@centos7-01 ~]# ansible webservers -m file -a 'path=/data/a.txt state=touch owner=root'
[root@centos7-02 data]# ll /data/a.txt
-rw-r--r-- 1 root root 0 May 23 20:58 /data/a.txt
#创建目录
[root@centos7-01 ~]# ansible webservers -m file -a 'path=/data/mysql state=directory'
#创建软链接
[root@centos7-01 ~]# ansible webservers -m file -a 'path=/data/mysql-5.7 state=directory'
[root@centos7-01 ~]# ansible webservers -m file -a 'src=/data/mysql-5.7 path=/data/mysql-link state=link'
#删除目录
[root@centos7-01 ~]# ansible webservers -m file -a 'path=/data/mysql-5.7 state=absent'
功能:检查文件或文件系统的状态
注意:对于Windows目标,改用[win_stat]模块。
选项:
path:文件/对象的完整路径(必须)
常用的返回值判断:
exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配
[root@centos7-01 ~]# ansible 127.0.0.1 -m stat -a 'path=/etc/passwd'
127.0.0.1 | SUCCESS => {
"changed": false,
"stat": {
"atime": 1653256465.281,
"attr_flags": "",
"attributes": [],
"block_size": 4096,
"blocks": 8,
"charset": "us-ascii",
"checksum": "9fb3b849ced4d15c76a056f5fe5d7a824304d165",
"ctime": 1652283848.738021,
"dev": 64768,
"device_type": 0,
"executable": false,
"exists": true,
"gid": 0,
"gr_name": "root",
"inode": 67790776,
"isblk": false,
"ischr": false,
"isdir": false,
"isfifo": false,
"isgid": false,
"islnk": false,
"isreg": true,
"issock": false,
"isuid": false,
"mimetype": "text/plain",
"mode": "0644",
"mtime": 1652283848.738021,
"nlink": 1,
"path": "/etc/passwd",
"pw_name": "root",
"readable": true,
"rgrp": true,
"roth": true,
"rusr": true,
"size": 1105,
"uid": 0,
"version": "42145232",
"wgrp": false,
"woth": false,
"writeable": true,
"wusr": true,
"xgrp": false,
"xoth": false,
"xusr": false
}
}
5.8、 unarchive 模块
anaconda-ks.cfg hellodb_MyISAM.sql mysql-5.7.37.tar.gz SCANIP.log ssh_key.sh test.sh
[root@centos7-01 ~]# ansible webservers -m unarchive -a 'src=mysql-5.7.37.tar.gz dest=/usr/local/src owner=root group=root'
[root@centos7-02 data]# cd /usr/local/src/
[root@centos7-02 src]# ll
total 4
drwxr-xr-x 34 root root 4096 Nov 29 20:18 mysql-5.7.37
打包压缩保存在被管理节点
[root@centos7-01 ~]# ansible webservers -m archive -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2 owner=chen mode=0600'
[root@centos7-02 data]# ll /data/log.tar.bz2
-rw-r--r-- 1 root root 549837 May 23 21:14 /data/log.tar.bz2
5.10、Hostname 模块
管理主机名,注意,此模块不修改“/etc/hosts”
[root@centos7-01 ~]# ansible 10.0.0.132 -m hostname -a 'name=nginx'
[root@centos7-02 data]# hostname
nginx
管理服务,控制远程主机上的服务
[root@centos7-04 ~]# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
[root@centos7-01 ~]# ansible 10.0.0.134 -m service -a 'name=httpd state=started enabled=yes'
[root@centos7-04 ~]# ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 [::]:80 [::]:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
功能:管理用户,管理用户帐户和用户属性
#创建用户
ansible 10.0.0.134 -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1 group=root'
ansible 10.0.0.134 -m user -a 'name=nginx comment=nginx uid=88 group=nginx groups="root,daemon" shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'
#remove=yes表示删除用户及家目录等数据,默认remove=no
[root@centos7-01 ~]# ansible 10.0.0.134 -m user -a 'name=nginx state=absent remove=yes'
管理组
[root@centos7-01 ~]# ansible webservers -m group -a 'name=nginx gid=88 system=yes'
[root@centos7-01 ~]# ansible webservers -m group -a 'name=nginx state=absent'
5.14、reboot 模块
重启,重新启动一台机器,等待它停机、恢复并响应命令
[root@centos7-01 ~]# ansible webservers -m reboot
功能: setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,会影响执行速度,playbooks会自动调用此模块,以收集有关的有用变量可以在剧本中使用的远程主机
可以使用 gather_facts:no 来禁止 Ansible 收集 facts 信息
[root@centos7-01 ~]# ansible 10.0.0.133 -m setup -a "filter=ansible_nodename"
10.0.0.133 | SUCCESS => {
"ansible_facts": {
"ansible_nodename": "centos7-03",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
[root@centos7-01 ~]# ansible 10.0.0.132 -m setup -a "filter=ansible_hostname"
10.0.0.132 | SUCCESS => {
"ansible_facts": {
"ansible_hostname": "nginx",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
[root@centos7-01 ~]# ansible 10.0.0.134 -m setup -a "filter=ansible_memtotal_mb"
10.0.0.134 | SUCCESS => {
"ansible_facts": {
"ansible_memtotal_mb": 1819,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
[root@centos7-01 ~]# ansible 10.0.0.132 -m setup -a "filter=ansible_processor_vcpus"
10.0.0.132 | SUCCESS => {
"ansible_facts": {
"ansible_processor_vcpus": 2,
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
[root@centos7-01 ~]# ansible 10.0.0.133 -m setup -a "filter=ansible_distribution_version"
10.0.0.133 | SUCCESS => {
"ansible_facts": {
"ansible_distribution_version": "7.9",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
[root@centos7-01 ~]# ansible 10.0.0.134 -m setup -a "filter=ansible_os_family"
10.0.0.134 | SUCCESS => {
"ansible_facts": {
"ansible_os_family": "RedHat",
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false
5.16、debug 模块
此模块可以用于输出信息,并且通过 msg 定制输出的信息内容,该模块在执行期间打印语句,对调试非常有用
注意:msg后面的变量有时需要加 ” ” 引起来
[root@centos7-01 ~]# ansible 10.0.0.132 -m debug
10.0.0.132 | SUCCESS => {
"msg": "Hello world!"
}
2、ansible-playbook实现MySQL的二进制部署
系统版本 CentOS 7.9
数据库版本 MySQL-5.7.36
服务器 10.0.0.131(主机名:centos7-01)
客户端 10.0.0.135(主机名:centos7-05)
源码包下载: https://cdn.mysql.com/archives/mysql-5.7/mysql-5.7.36-linux-glibc2.12-x86_64.tar.gz
一、服务器1配置
#1、CentOS 7.9 rpm包安装ansible
[root@centos7-01 ~]# yum install -y ansible
#2、版本信息
[root@centos7-01 ~]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Oct 14 2020, 14:45:30) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
#3、使用工具前需先配置ansible主控端能基于密钥认证,先修改下面一行,实现首次登录不显示询问提示
[root@centos7-01 ~]# vim /etc/ssh/ssh_config
# StrictHostKeyChecking ask 改为 StrictHostKeyChecking no
#4、检查对应服务器的host_key,建议取消此行注释,实现第一次连接自动信任目标主机
[root@centos7-01 ~]# vim /etc/ansible/ansible.cfg
host_key_checking = False
#5、配置主机清单
[root@centos7-01 ~]# vim /etc/ansible/hosts
[webservers]
10.0.0.135
二、基于key验证
[root@centos7-01 ~]# vim ssh_key.sh
#!/bin/bash
#密码
PASS=a123456
#设置网段最后的地址,4-255之间,越小扫描越快,可根据实际情况修改
END=254
IP=`ip a s eth0 | awk -F'[ /]+' 'NR==3{print $3}'`
NET=${IP%.*}.
rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
for((i=3;i<="$END";i++));do
ping -c 1 -w 1 ${NET}$i &> /dev/null && echo "${NET}$i" >> SCANIP.log &
done
wait
ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass || yum -y install sshpass
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP
AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done
#把.ssh/known_hosts拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/
done
三、创建mysql角色相关的目录
[root@centos7-01 ~]# mkdir -pv /data/ansible/
[root@centos7-01 ~]# cd /data/ansible/
[root@centos7-01 ansible]# mkdir roles
[root@centos7-01 ansible]# cd roles/
[root@centos7-01 roles]# mkdir -pv mysql/{tasks,files,vars}
mkdir: created directory ‘mysql’
mkdir: created directory ‘mysql/tasks’
mkdir: created directory ‘mysql/files’
mkdir: created directory ‘mysql/vars’
四、准备创建以下mysql角色相关的文件
[root@centos7-01 roles]# cd /data/ansible/roles/mysql/
[root@ansible mysql]#tree
.
├── files
│ ├── my.cnf
│ └── mysql-5.7.36-linux-glibc2.12-x86_64.tar.gz
├── tasks
│ ├── config.yml
│ ├── data.yml
│ ├── group.yml
│ ├── install.yml
│ ├── linkfile.yml
│ ├── main.yml
│ ├── path.yml
│ ├── script.yml
│ ├── secure.yml
│ ├── service.yml
│ ├── unarchive.yml
│ └── user.yml
└── vars
└── main.yml
#上传mysql-5.7.36-linux-glibc2.12-x86_64.tar到/data/ansible/roles/mysql/files/
[root@centos7-01 ]# cd /data/ansible/roles/mysql/files/
[root@centos7-01 files]# ls
mysql-5.7.36-linux-glibc2.12-x86_64.tar.gz
#配置my.cnf文件
[root@centos7-01 files]# vim my.cnf
[mysqld]
explicit_defaults_for_timestamp=true
server-id=1
log-bin
datadir=/data/mysql
socket=/data/mysql/mysql.sock
[mysqld_safe]
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock
#配置角色
[root@centos7-01 ]# cd /data/ansible/roles/mysql/
#配置vars/main.yml
[root@centos7-01 mysql]# vim vars/main.yml
mysql_version: 5.7.36
mysql_file: mysql-{{mysql_version}}-linux-glibc2.12-x86_64.tar.xz
mysql_root_password: 123456
#配置tasks/main.yml
[root@centos7-01 mysql]# vim tasks/main.yml
- include: install.yml
- include: group.yml
- include: user.yml
- include: unarchive.yml
- include: linkfile.yml
- include: data.yml
- include: config.yml
- include: script.yml
- include: path.yml
- include: service.yml
- include: secure.yml
#配置install.yml
[root@centos7-01 mysql]# vim tasks/install.yml
- name: install packages
yum:
name:
- libaio
- numactl-libs
#配置group.yml
[root@centos7-01 mysql]# vim tasks/group.yml
- name: create mysql group
group: name=mysql gid=306
#配置user.yml
[root@centos7-01 mysql]# vim tasks/user.yml
- name: create mysql user
user: name=mysql uid=306 group=mysql shell=/sbin/nologin system=yes create_home=no home=/data/mysql
#配置unarchive.yml
[root@centos7-01 mysql]# vim tasks/unarchive.yml
- name: copy tar to remote host and file mode
unarchive: src=/data/ansible/roles/mysql/files/mysql-5.7.36-linux-glibc2.12-x86_64.tar.gz dest=/usr/local/ owner=root group=root copy=yes
#配置linkfile.yml
[root@centos7-01 mysql]# vim tasks/linkfile.yml
- name: create linkfile /usr/local/mysql
file: src=/usr/local/mysql-5.7.36-linux-glibc2.12-x86_64 path=/usr/local/mysql state=link
#配置data.yml 数据库初始化
[root@centos7-01 mysql]# vim tasks/data.yml
#如果客户端没有/data/mysql数据库目录可加入- name: create /data/mysql生成文件夹
- name: create /data/mysql
file:
path=/data/mysql
state=directory
owner=mysql
group=mysql
- name: data dir
shell: /usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --datadir=/data/mysql
tags: data
#配置config.yml
[root@centos7-01 mysql]# vim tasks/config.yml
- name: config my.cnf
copy: src=/data/ansible/roles/mysql/files/my.cnf dest=/etc/my.cnf
#配置script.yml
[root@centos7-01 mysql]# vim tasks/script.yml
- name: service script
shell: /bin/cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
#配置path.yml
[root@centos7-01 mysql]# vim tasks/path.yml
- name: PATH variable
copy: content='PATH=/usr/local/mysql/bin:$PATH' dest=/etc/profile.d/mysql.sh
#配置service.yml
[root@centos7-01 mysql]# vim tasks/service.yml
- name: enable service
shell: chkconfig --add mysqld;/etc/init.d/mysqld start
tags: service
#配置secure.yml
[root@centos7-01 mysql]# vim tasks/secure.yml
- name: change password
shell: /usr/local/mysql/bin/mysqladmin -uroot password {{mysql_root_password}}
#在playbook中调用角色
[root@centos7-01 mysql]# cd /data/ansible/
[root@centos7-01 ansible]# vim role_mysql.yml
---
- hosts: webservers
remote_user: root
gather_facts: no
roles:
- mysql
五、运行playbook并查看结果
[root@centos7-01 ]#ansible-playbook role_mysql.yml
#登录10.0.0.135
[root@centos7-05 ]#ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 80 [::]:3306 [::]:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
#注意:安装完后要退出终端后再重新登录
[root@centos7-05 ]#mysql --version
mysql Ver 14.14 Distrib 5.7.36, for linux-glibc2.12 (x86_64) using EditLine wrapper
[root@centos7-05 ]#mysql -uroot -p123456
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
系统版本 CentOS 7.9
服务器 10.0.0.131(主机名:centos7-01)
客户端 10.0.0.134(主机名:centos7-04)
客户端 10.0.0.135(主机名:centos7-05)
关闭防火墙: systemctl disable –now firewalld
一、服务器1配置
#1、CentOS 7.9 rpm包安装ansible
[root@centos7-01 ~]# yum install -y ansible
#2、版本信息
[root@centos7-01 ~]# ansible --version
ansible 2.9.27
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Oct 14 2020, 14:45:30) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]
#3、使用工具前需先配置ansible主控端能基于密钥认证,先修改下面一行,实现首次登录不显示询问提示
[root@centos7-01 ~]# vim /etc/ssh/ssh_config
# StrictHostKeyChecking ask 改为 StrictHostKeyChecking no
#4、检查对应服务器的host_key,建议取消此行注释,实现第一次连接自动信任目标主机
[root@centos7-01 ~]# vim /etc/ansible/ansible.cfg
host_key_checking = False
#5、配置主机清单
[root@centos7-01 ~]# vim /etc/ansible/hosts
[webservers]
10.0.0.134
10.0.0.135
二、基于key验证
[root@centos7-01 ~]# vim ssh_key.sh
#!/bin/bash
#密码
PASS=a123456
#设置网段最后的地址,4-255之间,越小扫描越快,可根据实际情况修改
END=254
IP=`ip a s eth0 | awk -F'[ /]+' 'NR==3{print $3}'`
NET=${IP%.*}.
rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log
for((i=3;i<="$END";i++));do
ping -c 1 -w 1 ${NET}$i &> /dev/null && echo "${NET}$i" >> SCANIP.log &
done
wait
ssh-keygen -P "" -f /root/.ssh/id_rsa
rpm -q sshpass || yum -y install sshpass
sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP
AliveIP=(`cat SCANIP.log`)
for n in ${AliveIP[*]};do
sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done
#把.ssh/known_hosts拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
scp /root/.ssh/known_hosts ${n}:.ssh/
done
三、创建httpd角色相关的目录
[root@centos7-01 ~]# mkdir -pv /data/ansible/
[root@centos7-01 ~]# cd /data/ansible/
[root@centos7-01 ansible]# mkdir roles
[root@centos7-01 ansible]# cd roles/
[root@centos7-01 ~]# mkdir -pv /data/ansible/roles/httpd/{tasks,handlers,files,templates}
[root@centos7-01 ~]# cd /data/ansible/roles/httpd/
[root@centos7-01 httpd]# cat tasks/main.yml
- include: group.yml
- include: user.yml
- include: install.yml
- include: config.yml
- include: index.yml
- include: service.yml
[root@centos7-01 httpd]# cat tasks/group.yml
- name: create group apache
group: name=apache system=yes gid=80
[root@centos7-01 httpd]# cat tasks/user.yml
- name: create user apache
user: name=apache system=yes shell=/sbin/nologin home=/var/www uid=80 group=apache
[root@centos7-01 httpd]# cat tasks/install.yml
- name: install httpd
yum: name=httpd state=present
[root@centos7-01 httpd]# cat tasks/config.yml
- name: config file
copy: src=httpd.conf dest=/etc/httpd/conf/ backup=yes
notify: restart
[root@centos7-01 httpd]# cat tasks/index.yml
- name: index.html
template: src=index.html dest=/var/www/html/
[root@centos7-01 httpd]# cat tasks/service.yml
- name: start service
service: name=httpd state=started enabled=yes
[root@centos7-01 httpd]# cat templates/index.html
MY ADDRESS IS {{ ansible_eth0.ipv4.address }}
[root@centos7-01 httpd]# cat handlers//main.yml
- name: restart
service: name=httpd state=restarted
#在playbook中调用角色
[root@centos7-01 mysql]# cd /data/ansible/
[root@centos7-01 ansible]# vim role_httpd.yml
---
- hosts: webservers
remote_user: root
roles:
- httpd
四、运行playbook并查看结果
#语法检查
[root@centos7-01 ansible]# ansible-playbook -C role_httpd.yml
PLAY [webservers] *************************************************************************************************************************************************************************
TASK [Gathering Facts] ********************************************************************************************************************************************************************
ok: [10.0.0.134]
ok: [10.0.0.135]
TASK [httpd : create group apache] ********************************************************************************************************************************************************
changed: [10.0.0.135]
changed: [10.0.0.134]
TASK [httpd : create user apache] *********************************************************************************************************************************************************
changed: [10.0.0.135]
changed: [10.0.0.134]
TASK [install httpd] **********************************************************************************************************************************************************************
changed: [10.0.0.135]
changed: [10.0.0.134]
TASK [httpd : index.html] *****************************************************************************************************************************************************************
changed: [10.0.0.135]
changed: [10.0.0.134]
TASK [httpd : start service] **************************************************************************************************************************************************************
changed: [10.0.0.135]
changed: [10.0.0.134]
PLAY RECAP ********************************************************************************************************************************************************************************
10.0.0.134 : ok=6 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
10.0.0.135 : ok=6 changed=5 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
#执行安装
[root@centos7-01 ansible]# ansible-playbook role_httpd.yml
五、浏览器访问10.0.0.134和10.0.0.135进行验证
4、http的报文结构和状态码总结
http报文结构 http报文分请求报文和响应报文。
1.1 请求报文结构
请求报文由开始行、首部行和实体主体三部分构成(如下图)。
由上图可知:
①开始行的格式为“方法+空格+URL路径+空格+http版本”,回车换行后进入到首部行。
②开始行进入到首部行后,需输入首部字段名,例如http1.1版本要使用host头,加上“:”和空格,并接上对应的值如网址或主机ip等,回车键入下一行后再回车空一行进入实体主体部分。
③实体主体部分为数据部分,通常情况下为空,例如我们在浏览网页的时候基本使用的是GET方法。但是当我们使用POST方法等,进行用户名和密*码、文章等数据的上传时,实体主体部分不为空。
1.2 响应报文结构
与请求报文结构类似,响应报文也是由开始行、首部行和实体主体三部分组成(如下图)。
响应报文的开始行又称为状态行,包括http协议的版本、状态码(响应码)和解释状态码(响应码)的简单短语。响应报文的首部行包括响应时间、web服务器的类型及版本、最后修改日期等。首部行之后会空一行进入到实体主体部分,将数据返回给请求用户。
1.3 http报文结构范例
笔者这边做了一个很简单网页,只在网页中显示“hello world”,通过curl加-v选项去查看网页时能显示详情。客户端去查看网页时,“>”部分属于请求报文部分,因为使用的是GET方法,所以请求报文的实体主体部分为空;服务器接收到请求后会返回响应报文,为“<”部分内容,在开始行和首部行之后空一行将网页数据返回给请求用户(如下图)。
http状态码2.1 http状态码分类
http状态码是用以表示web服务器超文本传输协议响应状态的3位数字代码,大体可分为1-5开头的五类:
①1开头,例如100-101,属于信息提示,表示请求已被接收,等待进一步的处理;
②2开头,例如200-206,表示请求已被服务器成功接受、理解或接收;
③3开头,例如300-307,表示重定向,需要客户端采取进一步的操作才能完成请求;
④4开头,例如400-415,表示客户端错误;
⑤5开头,例如500-505,表示服务器在处理请求的过程中发生错误。
2.2 常见http状态码