1、主从复制及主主复制的实现
主从复制实现
#主节点和从节点安装mariadb
[15:37:51 root@centos8 ~]#dnf -y install mariadb-server
[15:40:07 root@centos8 ~]#vim /etc/my.cnf
#新增一下内容
[mysqld]
server-id=8
log-bin
[15:40:47 root@centos8 ~]#systemctl restart mariadb
[15:42:41 root@centos8 ~]#mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.3.28-MariaDB-log MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#查看二进制文件及位置
MariaDB [(none)]> show master logs;
+--------------------+-----------+
| Log_name | File_size |
+--------------------+-----------+
| mariadb-bin.000001 | 28265 |
| mariadb-bin.000002 | 344 |
+--------------------+-----------+
2 rows in set (0.000 sec)
#创建复制用户
MariaDB [(none)]> grant replication slave on *.* to repluser@'10.0.0.%' identified by 'madedu';
Query OK, 0 rows affected (0.001 sec)
#如果是mysql8.0,则需要两步实现
mysql>create user 'repluser'@'10.0.0.%';
mysql>grant replication slave on *.* to 'repluser'@'10.0.0.%';
#从节点
[root@centos8 ~]# cat /etc/my.cnf
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
[mysqld]
server-id=18
[root@centos8 ~]# systemctl restart mariadb
[root@centos8 ~]# mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 8
Server version: 10.3.28-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
MariaDB [(none)]> CHANGE MASTER TO MASTER_HOST='10.0.0.8', MASTER_USER='repluser', MASTER_PASSWORD='madedu', MASTER_PORT=3306, MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=344;
Query OK, 0 rows affected (0.007 sec)
MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.003 sec)
MariaDB [(none)]> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 10.0.0.8
Master_User: repluser
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mariadb-bin.000002
Read_Master_Log_Pos: 541
Relay_Log_File: mariadb-relay-bin.000002
Relay_Log_Pos: 754
Relay_Master_Log_File: mariadb-bin.000002
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 541
Relay_Log_Space: 1065
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
Last_IO_Errno: 0
Last_IO_Error:
Last_SQL_Errno: 0
Last_SQL_Error:
Replicate_Ignore_Server_Ids:
Master_Server_Id: 8
Master_SSL_Crl:
Master_SSL_Crlpath:
Using_Gtid: No
Gtid_IO_Pos:
Replicate_Do_Domain_Ids:
Replicate_Ignore_Domain_Ids:
Parallel_Mode: conservative
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
Slave_DDL_Groups: 1
Slave_Non_Transactional_Groups: 0
Slave_Transactional_Groups: 0
1 row in set (0.000 sec)
主主复制的实现
[15:37:51 root@centos8 ~]#dnf -y install mariadb-server
#在第一个节点上实现
[17:04:33 root@centos8 ~]#cat /etc/my.cnf
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
[mysqld]
server-id=8
log-bin
auto_increment_offset=1
auto_increment_increment=2
[17:04:37 root@centos8 ~]#systemctl start mariadb
[17:05:51 root@centos8 ~]#mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 10.3.28-MariaDB-log MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> show master logs;
+--------------------+-----------+
| Log_name | File_size |
+--------------------+-----------+
| mariadb-bin.000001 | 28495 |
| mariadb-bin.000002 | 344 |
+--------------------+-----------+
2 rows in set (0.000 sec)
MariaDB [(none)]> grant replication slave on *.* to repluser@'10.0.0.%' identified by 'magedu';
Query OK, 0 rows affected (0.000 sec)
#在第二个节点上实现
[root@centos8 ~]# vim /etc/my.cnf
[root@centos8 ~]# cat /etc/my.cnf
#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]
#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
[mysqld]
server-id=18
log-bin
auto_increment_offset=2 #开始点
auto_increment_increment=2 #增长幅度
[root@centos8 ~]# systemctl start mariadb
[root@centos8 ~]# mysql
MariaDB [(none)]> CHANGE MASTER TO MASTER_HOST='10.0.0.8', MASTER_USER='repluser', MASTER_PASSWORD='magedu', MASTER_PORT=3306, MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=344;
Query OK, 0 rows affected (0.008 sec)
MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.002 sec)
#在第一个master节点上实现
MariaDB [(none)]> CHANGE MASTER TO MASTER_HOST='10.0.0.8', MASTER_USER='repluser', MASTER_PASSWORD='magedu', MASTER_PORT=3306, MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=344;
Query OK, 0 rows affected (0.009 sec)
MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.001 sec)
#在两个节点上创建数据库
MariaDB [(none)]> create database db1;
Query OK, 1 row affected (0.001 sec)
MariaDB [(none)]> use db1
Database changed
MariaDB [db1]> create table t1(id int auto_increment primary key,name char(10));
Query OK, 0 rows affected (0.009 sec)
#在都第1个节点上执行
MariaDB [db1]> insert t1 (name) values('user1');
Query OK, 1 row affected (0.003 sec)
#在都第2个节点上执行
MariaDB [db1]> insert t1 (name) values('user2');
Query OK, 1 row affected (0.003 sec)
MariaDB [db1]> select * from t1;
+----+-------+
| id | name |
+----+-------+
| 1 | user1 |
| 2 | user1 |
| 4 | user1 |
| 6 | user2 |
+----+-------+
4 rows in set (0.000 sec)
2、xtrabackup实现全量+增量+binlog恢复库
3、MyCAT实现MySQL读写分离
#准备服务器
mycat-server 10.0.0.8 #内存建议2G以上
mysql-master 10.0.0.18 Mariadb 10.3.17
mysql-slave 10.0.0.28 Mariadb 10.3.17
#创建数据库
[20:30:19 root@centos8 ~]#yum -y install mariadb-server
#修改master和slave配置
#master的my.cnf
[root@mysql-master ~]# vim /etc/my.cnf
[mysqld]
server-id = 1
log-bin
#slave的my.cnf
[root@mysql-slave ~]# vim /etc/my.cnf
[mysqld]
server-id = 2
#启动mariadb服务器
[root@mysql-master ~]# systemctl start mariadb
[root@mysql-slave ~]# systemctl start mariadb
#在master创建复制用户
[root@mysql-master ~]# mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 10.3.28-MariaDB-log MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> grant replication slave on *.* to repluser@'10.0.0.%' identified by 'replpass';
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> show master status;
+--------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+--------------------+----------+--------------+------------------+
| mariadb-bin.000002 | 664 | | |
+--------------------+----------+--------------+------------------+
1 row in set (0.000 sec)
#slave上执行
[root@mysql-slave ~]# mysql
MariaDB [(none)]> CHANGE MASTER TO MASTER_HOST='10.0.0.18', MASTER_USER='repluser', MASTER_PASSWORD='replpass', MASTER_LOG_FILE='mariadb-bin.000002', MASTER_LOG_POS=664;
Query OK, 0 rows affected (0.015 sec)
MariaDB [(none)]> start slave;
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: 10.0.0.18
Master_User: repluser
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mariadb-bin.000002
Read_Master_Log_Pos: 664
Relay_Log_File: mariadb-relay-bin.000002
Relay_Log_Pos: 557
Relay_Master_Log_File: mariadb-bin.000002
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
Replicate_Do_DB:
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 664
Relay_Log_Space: 868
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: 0
Master_SSL_Verify_Server_Cert: No
Last_IO_Errno: 0
Last_IO_Error:
Last_SQL_Errno: 0
Last_SQL_Error:
Replicate_Ignore_Server_Ids:
Master_Server_Id: 1
Master_SSL_Crl:
Master_SSL_Crlpath:
Using_Gtid: No
Gtid_IO_Pos:
Replicate_Do_Domain_Ids:
Replicate_Ignore_Domain_Ids:
Parallel_Mode: conservative
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Slave has read all relay log; waiting for the slave I/O thread to update it
Slave_DDL_Groups: 0
Slave_Non_Transactional_Groups: 0
Slave_Transactional_Groups: 0
1 row in set (0.001 sec)
2、在MySQL代理服务器10.0.0.8安装mycat并启动
[21:05:29 root@mycat-server ~]#yum -y install java
[21:03:19 root@mycat-server ~]#java -version
openjdk version "1.8.0_312"
OpenJDK Runtime Environment (build 1.8.0_312-b07)
OpenJDK 64-Bit Server VM (build 25.312-b07, mixed mode)
#下载并安装
[21:04:52 root@mycat-server ~]#wget http://dl.mycat.org.cn/1.6.7.6/20210303094759/Mycat-server-1.6.7.6-release-20210303094759-linux.tar.gz
[21:05:29 root@mycat-server ~]#mkdir /apps
[21:06:40 root@mycat-server ~]#tar xvf Mycat-server-1.6.7.6-release-20210303094759-linux.tar.gz -C /apps/
[21:07:02 root@mycat-server ~]#echo 'PATH=/apps/mycat/bin:$PATH' > /etc/profile.d/mycat.sh
[21:08:34 root@mycat-server ~]#source /etc/profile.d/mycat.sh
#查看端口
[21:08:46 root@mycat-server ~]#ss -ntl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 100 127.0.0.1:25 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
#启动mycat
[21:09:15 root@mycat-server ~]#file /apps/mycat/bin/mycat
/apps/mycat/bin/mycat: POSIX shell script, ASCII text executable
[21:10:10 root@mycat-server ~]#mycat
Usage: /apps/mycat/bin/mycat { console | start | stop | restart | status | dump }
[21:10:51 root@mycat-server ~]#mycat start
Starting Mycat-server...
#查看端口,其中8066端口用于连接mycat
[21:11:14 root@mycat-server ~]#ss -ntlp
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=807,fd=4))
LISTEN 0 100 127.0.0.1:25 0.0.0.0:* users:(("master",pid=1041,fd=16))
LISTEN 0 1 127.0.0.1:32000 0.0.0.0:* users:(("java",pid=4701,fd=4))
LISTEN 0 128 *:9066 *:* users:(("java",pid=4701,fd=93))
LISTEN 0 128 [::]:22 [::]:* users:(("sshd",pid=807,fd=6))
LISTEN 0 100 [::1]:25 [::]:* users:(("master",pid=1041,fd=17))
LISTEN 0 50 *:45471 *:* users:(("java",pid=4701,fd=74))
LISTEN 0 50 *:1984 *:* users:(("java",pid=4701,fd=73))
LISTEN 0 50 *:34561 *:* users:(("java",pid=4701,fd=72))
LISTEN 0 128 *:8066 *:* users:(("java",pid=4701,fd=97))
#查看日志
[21:11:27 root@mycat-server ~]#tail /apps/mycat/logs/wrapper.log
STATUS | wrapper | 2022/06/12 21:11:14 | --> Wrapper Started as Daemon
STATUS | wrapper | 2022/06/12 21:11:14 | Launching a JVM...
INFO | jvm 1 | 2022/06/12 21:11:15 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
INFO | jvm 1 | 2022/06/12 21:11:15 | Copyright 1999-2006 Tanuki Software, Inc. All Rights Reserved.
INFO | jvm 1 | 2022/06/12 21:11:15 |
INFO | jvm 1 | 2022/06/12 21:11:16 | MyCAT Server startup successfully. see logs in logs/mycat.log
#在mycat 服务器上修改server.xml文件配置Mycat的连接信息
[21:27:50 root@mycat-server ~]#vim /apps/mycat/conf/server.xml
#或者删除注释,并修改下面行的8066改为3306
<property name="serverPort">3306</property>
<property name="managerPort">9066</property>
<property name="idleTimeout">300000</property>
<property name="authTimeout">15000</property>
<property name="bindIp">0.0.0.0</property>
<property name="dataNodeIdleCheckPeriod">300000</property> #5 * 60 * 1000L; //连
接空闲检查 删除#后面此部分
<property name="frontWriteQueueSize">4096</property> <property
name="processors">32</property> #--> 删除#后面此部分
.....
<user name="root"> #连接Mycat的用户名
<property name="password">magedu</property> #连接Mycat的密码
<property name="schemas">TESTDB</property> #数据库名要和schema.xml相
对应
</user>
</mycat:server>
#修改schema.xml实现读写分离策略
[21:49:45 root@mycat-server ~]#vim /apps/mycat/conf/schema.xml
[21:50:45 root@mycat-server ~]#cat /apps/mycat/conf/schema.xml
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">
<schema name="TESTDB" checkSQLschema="false" sqlMaxLimit="100" randomDataNode="dn1">
</schema>
<dataNode name="dn1" dataHost="localhost1" database="mycat" />
<dataHost name="localhost1" maxCon="1000" minCon="10" balance="1"
writeType="0" dbType="mysql" dbDriver="native" switchType="1" slaveThreshold="100">
<heartbeat>select user()</heartbeat>
<writeHost host="host1" url="10.0.0.18:3306" user="root"
password="123456">
<readHost host="host2" url="10.0.0.28:3306" user="root"
password="123456"/>
</writeHost>
</dataHost>
</mycat:schema>
[21:50:47 root@mycat-server ~]#mycat restart
#在后端住服务器创建用户并对mycat授权
MariaDB [(none)]> create database mycat;
Query OK, 1 row affected (0.002 sec)
MariaDB [(none)]> grant all on *.* to root@'10.0.0.%' identified by '123456';
Query OK, 0 rows affected (0.002 sec)
MariaDB [(none)]> flush privileges;
Query OK, 0 rows affected (0.001 sec)
#在MySQL中产看通用日志
MariaDB [(none)]> show variables like 'general_log'; #查看日志是否开启
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| general_log | OFF |
+---------------+-------+
1 row in set (0.002 sec)
MariaDB [(none)]> set global general_log=on; #开启日志
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> show variables like 'general_log_file'; #查看日志保存位置
+------------------+------------------+
| Variable_name | Value |
+------------------+------------------+
| general_log_file | mycat-server.log |
+------------------+------------------+
1 row in set (0.001 sec)
#在主和从服务器分别启用通用日志,查看读写分离
[root@mysql-slave ~]# vim /etc/my.cnf
[mysqld]
server-id = 2
general_log=ON
[root@mysql-slave ~]# systemctl restart mariadb
#停止从节点,MyCAT自动调度读请求至主节点
[root@mysql-slave ~]# systemctl stop mariadb
[root@mysql-master ~]# mysql
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 10
Server version: 10.3.28-MariaDB-log MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> select @@server_id;
+-------------+
| @@server_id |
+-------------+
| 1 |
+-------------+
1 row in set (0.000 sec)
MariaDB [(none)]>
4、ansible常用模块介绍
常用模块帮助文档参考:
https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html
https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html
Command 模块
功能:在远程主机执行命令,此为默认模块,可忽略 -m 选项
注意:此命令不支持 $VARNAME < > | ; & 等,可能用shell模块实现
注意:此模块不具有幂等性
Shell 模块
功能:和command相似,用shell执行命令,支持各种符号,比如:*,$, >
注意:此模块不具有幂等性
注意:调用bash执行命令 类似 cat /tmp/test.md | awk -F'|' '{print $1,$2}' &> /tmp/example.txt 这些
复杂命令,即使使用shell也可能会失败,解决办法:写到脚本时,copy到远程,执行,再把需要的结果
拉回执行命令的机器
Script 模块
功能:在远程主机上运行ansible服务器上的脚本(无需执行权限)
注意:此模块不具有幂等性
#范例
ansible websrvs -m script -a /data/test.sh
Copy 模块
功能:从ansible服务器主控端复制文件到远程主机
注意: src=file 如果是没指明路径,则为当前目录或当前目录下的files目录下的file文件
#如目标存在,默认覆盖,此处指定先备份
ansible websrvs -m copy -a "src=/root/test1.sh dest=/tmp/test2.sh owner=wang
mode=600 backup=yes"
#指定内容,直接生成目标文件
ansible websrvs -m copy -a "content='test line1\ntest line2\n'
dest=/tmp/test.txt"
#复制/etc目录自身,注意/etc/后面没有/
ansible websrvs -m copy -a "src=/etc dest=/backup"
#复制/etc/下的文件,不包括/etc/目录自身,注意/etc/后面有/
ansible websrvs -m copy -a "src=/etc/ dest=/backup"
Get_url 模块
功能: 用于将文件从http、https或ftp下载到被管理机节点上
常用参数如下:
url: 下载文件的URL,支持HTTP,HTTPS或FTP协议
dest: 下载到目标路径(绝对路径),如果目标是一个目录,就用服务器上面文件的名称,如果目标设置了名
称就用目标设置的名称
owner:指定属主
group:指定属组
mode:指定权限
force: 如果yes,dest不是目录,将每次下载文件,如果内容改变,替换文件。如果否,则只有在目标不存
在时才会下载该文件
checksum: 对目标文件在下载后计算摘要,以确保其完整性
示例: checksum="sha256:D98291AC[...]B6DC7B97",
checksum="sha256:http://example.com/path/sha256sum.txt"
url_username: 用于HTTP基本认证的用户名。 对于允许空密码的站点,此参数可以不使用
`url_password'
url_password: 用于HTTP基本认证的密码。 如果未指定`url_username'参数,则不会使用
`url_password'参数
validate_certs:如果“no”,SSL证书将不会被验证。 适用于自签名证书在私有网站上使用
timeout: URL请求的超时时间,秒为单位
Fetch 模块
功能:从远程主机提取文件至ansible的主控端,copy相反,目前不支持目录
范例:
[root@ansible ~]#ansible all -m fetch -a 'src=/etc/redhat-release
dest=/data/os'
[root@ansible ~]#tree /data/os/
/data/os/
├── 10.0.0.6
│ └── etc
│ └── redhat-release
├── 10.0.0.7
│ └── etc
│ └── redhat-release
└── 10.0.0.8
└── etc
└── redhat-release
6 directories, 3 files
File 模块
功能:设置文件属性,创建软链接等
范例:
#创建空文件
ansible all -m file -a 'path=/data/test.txt state=touch'
ansible all -m file -a 'path=/data/test.txt state=absent'
ansible all -m file -a "path=/root/test.sh owner=wang mode=755"
#创建目录
ansible all -m file -a "path=/data/mysql state=directory owner=mysql
group=mysql"
#创建软链接
ansible all -m file -a 'src=/data/testfile path|dest|name=/data/testfile-link
state=link'
#创建目录
ansible all -m file -a 'path=/data/testdir state=directory'
#递归修改目录属性,但不递归至子目录
ansible all -m file -a "path=/data/mysql state=directory owner=mysql
group=mysql"
#递归修改目录及子目录的属性
ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql
recurse=yes"
stat 模块
功能:检查文件或文件系统的状态
注意:对于Windows目标,请改用win_stat模块
常用的返回值判断:
exists: 判断是否存在
isuid: 调用用户的ID与所有者ID是否匹配
unarchive 模块
功能:解包解压缩
实现有两种用法:
1、将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes,此为默认值,可省略
2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no
常见参数:
copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,
会在远程主机上寻找src源文件
remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible
主机上
src:源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果
是远程主机上的路径,则需要设置copy=no
dest:远程主机上的目标路径
mode:设置解压缩后的文件权限
Archive 模块
功能:打包压缩保存在被管理节点
范例:
ansible websrvs -m archive -a 'path=/var/log/ dest=/data/log.tar.bz2 format=bz2
owner=wang mode=0600'
Hostname 模块
功能:管理主机名
范例:
ansible node1 -m hostname -a "name=websrv"
ansible 10.0.0.18 -m hostname -a 'name=node18.magedu.com'
Cron 模块
功能:计划任务
支持时间:minute,hour,day,month,weekday
范例:
#备份数据库脚本
[root@centos8 ~]#cat /root/mysql_backup.sh
#!/bin/bash
mysqldump -A -F --single-transaction --master-data=2 -q -uroot |gzip >
/data/mysql_`date +%F_%T`.sql.gz
#创建任务
ansible 10.0.0.8 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql"
job=/root/mysql_backup.sh'
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate ntp.aliyun.com
&>/dev/null' name=Synctime"
#禁用计划任务
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1
&>/dev/null' name=Synctime disabled=yes"
#启用计划任务
ansible websrvs -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1
&>/dev/null' name=Synctime disabled=no"
#删除任务
ansible websrvs -m cron -a "name='backup mysql' state=absent"
ansible websrvs -m cron -a 'state=absent name=Synctime'
Yum 和 Apt 模块
功能:
yum 管理软件包,只支持RHEL,CentOS,fedora,不支持Ubuntu其它版本
apt 模块管理 Debian 相关版本的软件包
范例:
ansible websrvs -m yum -a 'name=httpd state=present' #安装
ansible websrvs -m yum -a 'name=nginx state=present enablerepo=epel' #启用epel源
进行安装
ansible websrvs -m yum -a 'name=* state=lastest exclude=kernel*,foo*' #升级除
kernel和foo开头以外的所有包
ansible websrvs -m yum -a 'name=httpd state=absent' #删除
[root@ansible ~]#ansible websrvs -m yum -a 'name=sl,cowsay'
yum_repository 模块
范例: 创建和删除仓库
[root@ansible ~]#cat yum_repo.yml
[root@ansible ~]#ansible-playbook yum_repo.yml
[root@web1 ~]#cat /etc/yum.repos.d/external_repos.repo
[test]
baseurl = https://download.fedoraproject.org/pub/epel/$releasever/$basearch/
gpgcheck = 0
name = EPEL YUM repo
[root@ansible ~]#cat remove_yum_repo.yml
- hosts: websrvs
tasks:
- name: remove repo
yum_repository:
name: test
file: external_repos
state: absent
[root@ansible ~]#ansible-playbook remove_yum_repo.yml
Service 模块
功能:管理服务
范例:
ansible all -m service -a 'name=httpd state=started enabled=yes'
ansible all -m service -a 'name=httpd state=stopped'
ansible all -m service -a 'name=httpd state=reloaded'
ansible all -m shell -a "sed -i 's/^Listen 80/Listen 8080/'
/etc/httpd/conf/httpd.conf"
ansible all -m service -a 'name=httpd state=restarted'
User 模块
功能:管理用户
范例:
#创建用户
ansible all -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1
group=root'
ansible all -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
ansible all -m user -a 'name=nginx state=absent remove=yes'
#生成123456加密的密码
ansible localhost -m debug -a "msg={{ '123456'|
password_hash('sha512','salt')}}"
localhost | SUCCESS => {
"msg": "$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w."
}
#用上面创建的密码创建用户
ansible websrvs -m user -a 'name=test
password="$6$salt$MktMKPZJ6t59GfxcJU20DwcwQzfMvOlHFVZiOVD71w."'
#创建用户test,并生成4096bit的私钥
ansible websrvs -m user -a 'name=test generate_ssh_key=yes ssh_key_bits=4096
ssh_key_file=.ssh/id_rsa'
Group 模块
功能:管理组
范例:
#创建组
ansible websrvs -m group -a 'name=nginx gid=88 system=yes'
#删除组
ansible websrvs -m group -a 'name=nginx state=absent'
Lineinfile 模块
ansible在使用sed进行替换时,经常会遇到需要转义的问题,而且ansible在遇到特殊符号进行替换时,
存在问题,无法正常进行替换 。其实在ansible自身提供了两个模块:lineinfile模块和replace模块,可
以方便的进行替换
一般在ansible当中去修改某个文件的单行进行替换的时候需要使用lineinfile模块
regexp参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最
后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被
删除。
如果想进行多行匹配进行替换需要使用replace模块
功能:相当于sed,可以修改文件内容
范例:
ansible websrvs -m lineinfile -a "path=/etc/httpd/conf/httpd.conf
regexp='^Listen' line='Listen 80'"
ansible all -m lineinfile -a "path=/etc/selinux/config regexp='^SELINUX='
line='SELINUX=disabled'"
ansible all -m lineinfile -a 'dest=/etc/fstab state=absent regexp="^#"'
Replace 模块
该模块有点类似于sed命令,主要也是基于正则进行匹配和替换,建议使用
范例:
ansible all -m replace -a "path=/etc/fstab regexp='^(UUID.*)' replace='#\1'"
ansible all -m replace -a "path=/etc/fstab regexp='^#(UUID.*)' replace='\1'"
SELinux 模块
该模块管理 SELInux 策略
范例:
[root@ansible ~]#ansible 10.0.0.8 -m selinux -a 'state=disabled'
[WARNING]: SELinux state temporarily changed from 'enforcing' to 'permissive'.
State change will take effect next reboot.
10.0.0.8 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/libexec/platform-python"
},
"changed": true,
"configfile": "/etc/selinux/config",
"msg": "Config SELinux state changed from 'enforcing' to 'disabled'",
"policy": "targeted",
"reboot_required": true,
"state": "disabled"
}
[root@centos8 ~]#grep -v '#' /etc/selinux/config
SELINUX=disabled
SELINUXTYPE=targeted
[root@centos8 ~]#getenforce
Permissive
reboot 模块
[root@ansible ~]#ansible websrvs -m reboot
mount 挂载和卸载
功能: 挂载和卸载文件系统
范例:
#临时挂载
mount websrvs -m mount -a 'src="UUID=b3e48f45-f933-4c8e-a700-22a159ec9077"
path=/home fstype=xfs opts=noatime state=present'
#临时取消挂载
mount websrvs -m mount -a 'path=/home fstype=xfs opts=noatime state=unmounted'
#永久挂载
ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/
uploads opts="_netdev" state=mounted'
#永久卸载
ansible websrvs -m mount -a 'src=10.0.0.8:/data/wordpress path=/var/www/html/wpcontent/
uploads state=absent'
Setup 模块
功能: setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机
较多,会影响执行速度
可以使用gather_facts: no 来禁止 Ansible 收集 facts 信息
范例:
ansible all -m setup
ansible all -m setup -a "filter=ansible_nodename"
ansible all -m setup -a "filter=ansible_hostname"
ansible all -m setup -a "filter=ansible_domain"
ansible all -m setup -a "filter=ansible_memtotal_mb"
ansible all -m setup -a "filter=ansible_memory_mb"
ansible all -m setup -a "filter=ansible_memfree_mb"
ansible all -m setup -a "filter=ansible_os_family"
ansible all -m setup -a "filter=ansible_distribution_major_version"
ansible all -m setup -a "filter=ansible_distribution_version"
ansible all -m setup -a "filter=ansible_processor_vcpus"
ansible all -m setup -a "filter=ansible_all_ipv4_addresses"
ansible all -m setup -a "filter=ansible_architecture"
ansible all -m setup -a "filter=ansible_uptime_seconds"
ansible all -m setup -a "filter=ansible_processor*"
ansible all -m setup -a 'filter=ansible_env'
debug 模块
此模块可以用于输出信息,并且通过 msg 定制输出的信息内容
注意: msg后面的变量有时需要加 " " 引起来