首页
归档
时光轴
推荐
Cloud
图床
导航
Search
1
Deploy OpenStack offline based on Kolla
745 阅读
2
openstact 基础环境安装 (手动版)
689 阅读
3
Mariadb 主从复制&读写分离
651 阅读
4
Typecho 1.2.0 部署
643 阅读
5
FusionCompute8.0 体验
576 阅读
Python
Linux
随笔
mysql
openstack
Search
标签搜索
linux
Pike
python
爬虫
openstack
mysql
Essay
Ansible
docker
Zabbix
kolla
Internet
Redis
1+X
Hyper-V
jenkins
Kickstart
自动化
sh
pxe
Acha
累计撰写
77
篇文章
累计收到
1
条评论
首页
栏目
Python
Linux
随笔
mysql
openstack
页面
归档
时光轴
推荐
Cloud
图床
导航
搜索到
28
篇与
的结果
2021-10-07
CentOS7 Zabbix5.0 分布安装
zabbix5.0 分布安装 环境规划 主机名 IP 环境 zabbix-server 10.35.172.76 zabbix-server、zabbix-agent zabbix-web 10.35.172.77 nginx、php7.2 zabbix-db 10.35.172.78 mysql5.7 zabbix-db # 安装 MySQL5.7 Yum 源 rpm -ivh http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm # 检查 Yum 源 ls /etc/yum.repos.d/ yum repolist enabled | grep mysql # 安装 & 启动 MySQL yum install mysql-community-server -y systemctl start mysqld && systemctl enable mysqld # 修改root密码, 创建zabbix数据库及用户并授权,刷新权限 grep 'temporary password' /var/log/mysqld.log mysql -uroot -pds,GLkvre7fG mysql> ALTER USER root@localhost IDENTIFIED BY 'P@ssw0rd'; mysql> create database zabbix character set utf8 collate utf8_bin; mysql> create user 'zabbix'@'%' identified by 'P@ssw0rd'; mysql> grant all privileges on zabbix.* to 'zabbix'@'%'; mysql> flush privileges; # 导入数据(create.sql.gz由zabbix-server主机拷贝) zcat create.sql.gz | mysql -uzabbix -pP@ssw0rd zabbix zabbix-web # 安装 PHP7 Yum 源 rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm # 安装 php7.2 及相关插件 yum install php72w-fpm php72w-gd.x86_64 php72w-bcmath.x86_64 php72w-xml.x86_64 php72w-mbstring.x86_64 php72w-ldap.x86_64 php72w-mysqlnd.x86_64 -y # 检查 php版本 php-fpm -v # 安装 Nginx yum install nginx -y # 生成 Nginx 模板文件 grep -Ev "#|^$" /etc/nginx/nginx.conf.default > /etc/nginx/nginx.conf # cp php 相关片段 vim /etc/nginx/nginx.conf.default #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # 修改配置文件 vim /etc/nginx/nginx.conf # 修改 root 目录 index # 删除 error 模块 # 添加 php相关片段 # 创建 Nginx 网页目录 mkdir /html # 检查 Nginx 语法 nginx -t # 启动 Nginx & php systemctl start nginx && systemctl enable nginx systemctl start php-fpm && systemctl enable php-fpm # 下载 Zabbix 软件包 wget https://cdn.zabbix.com/zabbix/sources/stable/5.0/zabbix-5.0.16.tar.gz # 解压 & cp 前端文件 到 网页目录 tar xf zabbix-5.0.16.tar.gz cp -a /root/zabbix-5.0.16/ui/* /html # 目录授权 chown -R nginx:nginx /html # 创建 session 目录,并授权 mkdir /var/lib/php/session chown -R nginx:nginx /var/lib/php/session # 修改 php.ini 配置文件 vim /etc/php.ini # max_execution_time = 300 # max_input_time = 300 # post_max_size = 16M # date.timezone = Asia/Shanghai # 重启生效配置文件 systemctl restart php-fpm # 上传字体文件,并替换 cd /html/assets/fonts mv simhei.ttf DejaVuSans.ttf zabbix-server # 安装 Zabbix Yum源 rpm -ivh https://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm # 替换 Yum仓库 sed -i 's#http://repo.zabbix.com#https://mirrors.tuna.tsinghua.edu.cn/zabbix#g' /etc/yum.repos.d/zabbix.repo # 安装 zabbix-server yum install zabbix-server-mysql -y # 将 create.sql.gz 拷贝至 zabbix-db scp /usr/share/doc/zabbix-server-mysql-5.0.16/create.sql.gz 10.35.172.78:/root # 配置 zabbix-server 中的 DB vim /etc/zabbix/zabbix_server.conf # DBHost=localhost # DBName=zabbix # DBUser=zabbix # DBPassword=123456 # 启动 Zabbix-server systemctl start zabbix-server && systemctl enable zabbix-server # 安装 net-tools,检查 服务端口 yum install -y net-tools netstat -lntp # 安装 & 启动 zabbix-agent yum install -y zabbix-agent systemctl start zabbix-agent && systemctl enable zabbix-agent 访问 10.35.172.77 配置使用 zabix
2021年10月07日
208 阅读
0 评论
0 点赞
2021-10-06
CentOS7 安装 Zabbix4.0
CentOS7 安装 Zabbix4.0 准备 Yum 源 # 备份 Yum 源 mkdir /etc/yum.repos.d/bak mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/bak # CentOS7 Zabbix4.0 Yum源 echo "[zabbix] name=Zabbix Official Repository - $basearch baseurl=https://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/4.0/rhel/7/$basearch/ enabled=1 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX-A14FE591 [zabbix-debuginfo] name=Zabbix Official Repository debuginfo - $basearch baseurl=https://mirrors.tuna.tsinghua.edu.cn/zabbix/zabbix/4.0/rhel/7/$basearch/debuginfo/ enabled=0 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX-A14FE591 gpgcheck=1 [zabbix-non-supported] name=Zabbix Official Repository non-supported - $basearch baseurl=https://mirrors.tuna.tsinghua.edu.cn/zabbix/non-supported/rhel/7/$basearch/ enabled=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX gpgcheck=1" > /etc/yum.repos.d/zabbix.repo # epel & CentOS7.5(1804) Yum源 echo "[epel] name=epel baseurl=https://mirrors.tuna.tsinghua.edu.cn/epel/7/x86_64/ gpgcheck=0 enabled=1 [centos] name=centos baseurl=https://mirrors.tuna.tsinghua.edu.cn/centos-vault/7.5.1804/os/x86_64/ gpgcheck=0 enabled=1" > /etc/yum.repos.d/repo.repo # 清除缓存,查看 Yum 列表 yum clean all yum repolist 下载 服务端程序 yum install -y zabbix-server-mysql zabbix-web-mysql yum install -y mariadb-server 配置 数据库 systemctl start mariadb && systemctl enable mariadb mysql_secure_installation #回车 第一个N 其他Y mysql MariaDB [(none)]> create database zabbix character set utf8 collate utf8_bin; MariaDB [(none)]> grant all privileges on zabbix.* to zabbix@'%' identified by 'zabbix'; cd /usr/share/doc/zabbix-server-mysql-4.0.34/ zcat create.sql.gz | mysql -uzabbix -pzabbix zabbix 配置 服务端 vim /etc/zabbix/zabbix_server.conf # 修改 连接数据库相关配置 # DBHost=localhost < 数据库 IP > # DBName=zabbix < 数据库名> # DBUser=zabbix < 数据库用户> # DBPassword=zabbix < 数据库密码> vim /etc/httpd/conf.d/zabbix.conf # 修改时区 (去除注释) # php_value date.timezone Asia/Shanghai systemctl start zabbix-server && systemctl enable zabbix-server systemctl start httpd && systemctl enable httpd yum install -y net-tools netstat -lntp # 检查 是否有 Zabbix-server (10051) 端口 # 登录 zabbix 网页设置 添加 监控主机 yum install -y zabbix-agent vi /etc/zabbix/zabbix_agentd.conf # 修改服务端 IP # Server=127.0.0.1 systemctl start zabbix-agent && systemctl enable zabbix-agent # 网页添加 监控主机
2021年10月06日
240 阅读
0 评论
0 点赞
2021-08-06
kvm虚拟化基础
KVM虚拟化 虚拟化,通过模拟计算机的硬件,来实现在同一台计算机上同时运行多个不同的操作系统的技术。 宿主机 内存 大于 4G 纯净的操作系统 ( 版本做好为稳定版) 关闭 selinux && firewalld && NetworkManager systemctl stop firewall && systemctl disbale firewalld systemctl stop NetworkManager && systemctl disbale NetworkManager setenforce 0 && sed -i 's/SELINUX=.*/SELINUX=permissive/g' /etc/selinux/config linux 虚拟化软件的差别 linux虚拟化软件 qemu 软件纯模拟全虚拟化软件,特别慢!兼容性好! xen(半) 性能特别好,需要使用专门修改之后的内核,兼容性差! kvm(linux) 全虚拟化,它有硬件支持cpu,内置在linux内核模块,而且不需要使用专门的内核 vmware workstations 图形界面 virtual box 图像化界面 安装 kvm 虚拟化管理工具 kvm kernel-based virtual machine libvirt 作用:管理虚拟机 虚拟类型:kvm,xen,qemu 等 virt 作用:安装、克隆虚拟机的工具(virt-install\virt-clone) qemu-kum、qemu-img 作用:管理虚拟机的虚拟磁盘 配置 base 源 curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo 安装 rpm包 yum install libvirt virt-install qemu-kvm -y 启动 libvirtd systemctl start libvirtd.service && systemctl enable libvirtd.service 安装一台kvm虚拟机 virt-install --virt-type kvm --os-type=linux --os-variant rhel7 --name centos7 \ --memory 1024 --vcpus 1 --disk /opt/centos7.raw,format=raw,size=10 \ --cdrom /opt/CentOS-7-x86_64-DVD-1708.iso \ --network network=default --graphics vnc,listen=0.0.0.0 --noautoconsole --virt-type kvm 虚拟化的类型(qemu) --os-type=linux 系统类型 --os-variant rhel7 系统版本 --name centos7 虚拟机的名字 (必须唯一) --memory 1024 虚拟机的内存 --vcpus 1 虚拟cpu的核数 --disk /opt/centos2.raw,format=raw,size=10(必须唯一) --cdrom /opt/CentOS-7-x86_64-DVD-1708.iso 系统光盘 --network network=default 使用默认NAT的网络 --graphics vnc,listen=0.0.0.0 --noautoconsole (可有可无) VNC 连接 IP:5900 安装系统注意事项: 分区 只保留根分区 关闭内核奔溃备份机制(KDUMP) 打开网卡开机自启 修改时区 亚洲/上海 安装重启后在宿主机启动虚拟机 virsh 管理&配置 # 查看虚拟机列表(--all) virsh list # 查询 VNC 端口号 virsh vncdisplay <host> # 开启虚拟机 virsh start <host> # 关闭虚拟机 virsh shutdown <host> # 断电关机 virsh destroy <host> # 重启虚拟机 virsh reboot <host> # 挂起虚拟机 virsh suspend <host> # 恢复虚拟机 virsh resume <host> # 开机自启 (注:libvirtd 开机自启) virsh autostart <host> # 取消开机自启 virsh autostart --disable <host> # 导出配置 virsh dumpxml centos7 > vm_centos7.xml # 删除配置 (先关机) virsh undefine centos7 # 导入配置 (重启生效) virsh define vm_centos7.xml # 修改配置 virsh edit centos7 # 重命名虚拟机 (低版本不支持) virsh domrename centos7 web01 ## kvm 虚拟机允许console登录 (注:在 kvm虚拟机内操作) grubby --update-kernel=ALL --args="console=ttyS0,115200n8" reboot # console登录虚拟机 virsh console centos7 虚拟磁盘管理 raw: 俗称裸格式,占用空间比较大,不支持快照功能,不方便传输 ,读写性能较好 qcow2: qcow(copy on write)的升级版,占用空间小,支持快照,性能比raw差一点,方便传输 # 查看虚拟磁盘信息 qemu-img info test.qcow2 # 创建虚拟硬盘 qemu-img create -f qcow2 test.qcow2 2G # 调整磁盘磁盘容量(只增不减) qemu-img resize test.qcow2 +20G # 磁盘格式转换 qemu-img convert -f raw -O qcow2 oldboy.raw oldboy.qcow2 # 调整虚拟机磁盘格式 # 1. 格式转换 qemu-img convert -f raw -O qcow2 oldboy.raw web01.qcow2 # 2. 修改配置文件 virsh edit web01 # 修改 格式和路径 # <driver name='qemu' type='qcow2'/> # <source file='/opt/web01.qcow2'/> # 3. 重启虚拟机 virsh destroy web01 virsh start web01 快照管理 # 创建快照 virsh snapshot-create-as centos7 --name install_ok # 查看快照 virsh snapshot-list centos7 # 还原快照 virsh snapshot-revert centos7 --snapshotname install_ok # 删除快照 virsh snapshot-delete centos7 --snapshotname install_ok # raw不支持做快照,qcow2支持快照,并且快照就保存在qcow2的磁盘文件中 虚拟机克隆 完整克隆 自动 virt-clone --auto-clone -o centos7 -n web02 手动(可以压缩空间 -c) # 1.生成磁盘文件 qemu-img convert -f qcow2 -O qcow2 -c web02.qcow2 web03.qcow2 -c # 2.导出虚拟机配置文件 virsh dumpxml web02 >web03.xml # 3.修改虚拟机配置 vim web03.xml ## 修改虚拟机的名字 ## 删除虚拟机uuid ## 删除mac地址mac add ## 修改磁盘路径disk # 4.导入虚拟机配置 virsh define web03.xml # 5.启动虚拟机 virsh start web03 链接克隆 手动 # 1.生成虚拟机磁盘文件 qemu-img create -f qcow2 -b web03.qcow2 web04.qcow2 # 2.生成虚拟机配置文件 virsh dumpxml web03 >web04.xml # 3.修改虚拟机配置文件 vim web04.xml ##修改虚拟机的名字 ##删除虚拟机uuid ##删除mac地址 ##修改磁盘路径 # 4.导入虚拟机并进行启动测试 virsh define web04.xml # 5.启动虚拟机 virsh start web04 自动(脚本) [root@kvm scripts]# cat link_clone.sh #!/bin/bash old_vm=$1 new_vm=$2 #a:生成虚拟机磁盘文件 old_disk=`virsh dumpxml $old_vm|grep "<source file"|awk -F"'" '{print $2}'` disk_tmp=`dirname $old_disk` qemu-img create -f qcow2 -b $old_disk ${disk_tmp}/${new_vm}.qcow2 #b:生成虚拟机的配置文件 virsh dumpxml $old_vm >/tmp/${new_vm}.xml #修改虚拟机的名字 sed -ri "s#(<name>)(.*)(</name>)#\1${new_vm}\3#g" /tmp/${new_vm}.xml #删除虚拟机uuid sed -i '/<uuid>/d' /tmp/${new_vm}.xml #删除mac地址 sed -i '/<mac address/d' /tmp/${new_vm}.xml #修改磁盘路径 sed -ri "s#(<source file=')(.*)('/>)#\1${disk_tmp}/${new_vm}.qcow2\3#g" /tmp/${new_vm}.xml #c:导入虚拟机并进行启动测试 virsh define /tmp/${new_vm}.xml virsh start ${new_vm} sh link_clone.sh centos7 web05
2021年08月06日
240 阅读
0 评论
0 点赞
2021-07-19
Mariadb 主从复制&读写分离
数据库 主从&读写分离 节点规划 IP 主机名 节点 10.35.172.77 mysql1 主数据库节点 10.35.172.78 mysql2 从数据库节点 10.35.172.79 mycat 数据库中间件节 1、基础环境搭建 ### mysql1 # 修改主机名 [root@mysql1 ~]# hostnamectl set-hostname mysql1 # 配置解析文件 [root@mysql1 ~]# echo "10.35.172.77 mysql1 10.35.172.78 mysql2" >> /etc/hosts # 关闭 selinux&防火墙 [root@mysql1 ~]# setenforce 0 [root@mysql1 ~]# systemctl stop firewalld # SecureXF上传 mariad-repo.tar.gz && 解压到 /opt [root@mysql1 ~]# tar -zxvf mariadb-repo.tar.gz -C /opt # 配置yum源 [root@mysql1 ~]# mkdir /etc/yum.repo.d/bak [root@mysql1 ~]# mv /etc/yum.repo.d/* /bak [root@mysql1 ~]# echo "[mariadb] name=mariadb baseurl=file:///opt/mariadb-repo gpgcheck=0 enabled=1 [centos] name=centos baseurl=ftp://10.35.172.81/centos gpgcheck=0 enabled=1" > /etc/yum.repos.d/local.repo ### mysql2 [root@mysql2 ~]# hostnamectl set-hostname mysql2 [root@mysql2 ~]# echo "10.35.172.77 mysql1 10.35.172.78 mysql2" >> /etc/hosts [root@mysql2 ~]# setenforce 0 [root@mysql2 ~]# systemctl stop firewalld # SecureXF 上传 mariad-repo.tar.gz [root@mysql1 ~]# tar -zxvf mariadb-repo.tar.gz -C /opt [root@mysql2 ~]# mkdir /etc/yum.repo.d/bak [root@mysql2 ~]# mv /etc/yum.repo.d/* /bak [root@mysql2 ~]# echo "[mariadb] name=mariadb baseurl=file:///opt/mariadb-repo gpgcheck=0 enabled=1 [centos] name=centos baseurl=ftp://10.35.172.81/centos gpgcheck=0 enabled=1" > /etc/yum.repos.d/local.repo ### mycat [root@mycat ~]# hostnamectl set-hostname mycat [root@mycat ~]# setenforce 0 [root@mycat ~]# systemctl stop firewalld [root@mycat ~]# mkdir /etc/yum.repo.d/bak [root@mycat ~]# mv /etc/yum.repo.d/* /bak # SecureXF 上传 mariad-repo.tar.gz [root@mycat ~]# tar -zxvf mariadb-repo.tar.gz -C /opt [root@mycat ~]# echo "[mariadb] name=mariadb baseurl=file:///opt/mariadb-repo gpgcheck=0 enabled=1 [centos] name=centos baseurl=ftp://10.35.172.81/centos gpgcheck=0 enabled=1" > /etc/yum.repos.d/local.repo 2、安装服务 # 安装 mariadb 并启动 [root@mysql1 ~]# yum install -y mariadb mariadb-server [root@mysql1 ~]# systemctl start mariadb && systemctl enable mariadb [root@mysql2 ~]# yum install -y mariadb mariadb-server [root@mysql2 ~]# systemctl start mariadb && systemctl enable mariadb # 初始化mariadb [root@mysql1 ~]# mysql_secure_installation ## 注意:Disallow root login remotely? [Y/n] n ## 其他为 yes ;密码设置为 000000 [root@mysql2 ~]# mysql_secure_installation ## 注意:Disallow root login remotely? [Y/n] n ## 其他为 yes ;密码设置为 000000 # 安装JDK & 查看JDK版本 [root@mycat ~]# yum install -y java-1.8.0-openjdk java-1.8.0-openjdk-devel [root@mycat ~]# java -version # 二进制安装 mycat ## SecureXF 上传 Mycat-server-1.6-RELEASE-20161028204710-linux.tar.gz [root@mycat ~]# tar -zxvf Mycat-server-1.6-RELEASE-20161028204710-linux.tar.gz -C /usr/local/ # 配置环境变量 [root@mycat ~]# echo export MYCAT_HOME=/usr/local/mycat/ >> /etc/profile [root@mycat ~]# source /etc/profile 3、配置服务 ### 主从复制 # mysql1 [root@mysql1 ~]# vi/etc/my.cnf.d/server.cnf # 在 [mysqld]标签下添加 log_bin = mysql-bin #记录操作日志 binlog_ignore_db = mysql #不同步mysql系统数据库 server_id = 77 #数据库集群中的每个节点id都要不同 # 重启数据库 [root@mysql1 ~]# systemctl restart mariadb # 进入数据库并配置 [root@mysql1 ~]# mysql -uroot -p000000 MariaDB [(none)]> grant all privileges on *.* to root@'%' identified by "000000"; MariaDB [(none)]> grant replication slave on *.* to 'user'@'mysql2' identified by '000000'; # mysql2 [root@mysql2 ~]# vi/etc/my.cnf.d/server.cnf # 在 [mysqld]标签下添加 log_bin = mysql-bin binlog_ignore_db = mysql server_id = 78 [root@mysql2 ~]# systemctl restart mariadb [root@mysql2 ~]# mysql -uroot -p000000 MariaDB [(none)]> change master to master_host='mysql1',master_user='user',master_password='000000'; ### 读写分离 # mycat # schema.xml配置文件 ;将原内容替换为下面文字 [root@mycat ~]# vi /usr/local/mycat/conf/schema.xml <?xml version="1.0"?> <!DOCTYPE mycat:schema SYSTEM "schema.dtd"> <mycat:schema xmlns:mycat="http://io.mycat/"> <schema name="USERDB" checkSQLschema="true" sqlMaxLimit="100" dataNode="dn1"></schema> <dataNode name="dn1" dataHost="localhost1" database="test" /> <dataHost name="localhost1" maxCon="1000" minCon="10" balance="3" dbType="mysql" dbDriver="native" writeType="0" switchType="1" slaveThreshold="100"> <heartbeat>select user()</heartbeat> <writeHost host="hostM1" url="172.30.11.12:3306" user="root" password="000000"> <readHost host="hostS1" url="172.30.11.13:3306" user="root" password="000000" /> </writeHost> </dataHost> </mycat:schema> # 修改配置文件权限 [root@mycat ~]# chown root:root /usr/local/mycat/conf/schema.xml # 编辑mycat的访问用户 [root@mycat ~]# vi /usr/local/mycat/conf/server.xml # 在配置文件的最后部分,修改 password schemas <user name="root"> <property name="password">000000</property> <property name="schemas">USERDB</property # 然后删除如下几行: <user name="user"> <property name="password">user</property> <property name="schemas">TESTDB</property> <property name="readOnly">true</property> </user> # 启动Mycat服务 [root@mycat ~]# /bin/bash /usr/local/mycat/bin/mycat start 4、验证 ### 主从复制 # mysql2 # 登录查询主从状态 [root@mysql2 ~]# mysql -uroot -p000000 MariaDB [(none)]> start slave; MariaDB [(none)]> show slave status\G # mysql1 创建库test,并在库test中创建表company,插入表数据 [root@mysql1 ~]# mysql -uroot -p000000 MariaDB [(none)]> create database test; MariaDB [(none)]> use test; MariaDB [test]> create table company(id int not null primary key,name varchar(50),addr varchar(255)); MariaDB [test]> insert into company values(1,"alibaba","china"); MariaDB [test]> select * from company; # mysql2 查看数据库列表。找到test数据库,查询表 验证从数据库的复制 [root@mysql2 ~]# mysql -uroot -p000000 MariaDB [(none)]> use test; MariaDB [test]> show tables; MariaDB [test]> select * from company; ### 读写分离 # 安装客户端工具 [root@mycat ~]# yum install -y MariaDB-client # 使用mysql命令查看Mycat服务的逻辑库USERDB [root@mycat ~]# mysql -h127.0.0.1 -P8066 -uroot -p000000 MySQL [(none)]> show databases; MySQL [(none)]> use USERDB MySQL [USERDB]> show tables; MySQL [USERDB]> select * from company; # 使用mysql命令对表company添加一条数据 MySQL [USERDB]> insert into company values(2,"bastetball","usa"); MySQL [USERDB]> select * from company; # 验证Mycat服务对数据库读写操作分离 [root@mycat ~]# mysql -h127.0.0.1 -P9066 -uroot -p000000 -e 'show @@datasource;'
2021年07月19日
651 阅读
0 评论
0 点赞
2021-07-16
ansible 第二版
主机清单 简介 基础知识 格式 主机 & 组 变量 继承 调用 常见格式 ini [root@ansible project]# cat hosts mail.example.com www[01:50].example.com: jumper ansible_port=5555 ansible_host=192.0.2.50 [webservers] foo.example.com bar.example.com [dbservers] one.example.com two.example.com three.example.com [webservers:vars] http_port: 8080 [servers:children] webservers dbservers yaml [root@ansible project]# cat hosts all: hosts: foo.example.com www[01:50].example.com: mysql01: ansible_host: 192.168.100.10 ansible_port: 22 vars: ntp_server: net.atlanta.example.com http_port: 8080 children: webservers: hosts: foo.example.com: bar.example.com: dbservers: hosts: one.example.com: two.example.com: three.example.com: 主机清单文件 (inventory) # 主机 + 密码 + 端口 ansible_host=192.168.100.10 ansible_port=2222 ansible_user=root ansible_password=123456 # 别名 + 主机 jumper ansible_host=192.0.2.50 # 主机 + 组(密钥) [webservers] 192.168.100.12 192.168.100.13 ad-hoc Ansible ad-hoc 在一个或多个受管节点上自动执行单个任务 格式 ansible <pattern> -m <module_name> -a "<module_name>"" < pattern > 主机 模块名 模块选项 体验 ping 模块 [root@ansible ansible]# ansible youto -m ping -i hosts 10.35.172.74 | SUCCESS => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python" }, "changed": false, "ping": "pong" } [root@ansible ansible]# ansible youto -i hosts --list-host hosts (1): 10.35.172.74 playbook yum 选项 解释 参数 name 软件名 httpd、httpd-2.4、url state 状态 latest、present、absent exclude 排除 kernel* enablerepo 仓库 centos Examples # 安装最新的 httpd - name: install the latest version of Apache yum: name: httpd state: latest # - name: ensure a list of packages installed yum: name: "{{ packages }}" vars: packages: - httpd - httpd-tools - name: remove the Apache package yum: name: httpd state: absent - name: install the latest version of Apache from the testing repo yum: name: httpd enablerepo: testing state: present - name: install one specific version of Apache yum: name: httpd-2.2.29-1.4.amzn1 state: present - name: upgrade all packages yum: name: '*' state: latest - name: upgrade all packages, excluding kernel & foo related packages yum: name: '*' state: latest exclude: kernel*,foo* - name: install the nginx rpm from a remote repo yum: name: http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state: present - name: install nginx rpm from a local file yum: name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state: present - name: install the 'Development tools' package group yum: name: "@Development tools" state: present - name: install the 'Gnome desktop' environment group yum: name: "@^gnome-desktop-environment" state: present - name: List ansible packages and register result to print with debug later. yum: list: ansible register: result - name: Install package with multiple repos enabled yum: name: sos enablerepo: "epel,ol7_latest" - name: Install package with multiple repos disabled yum: name: sos disablerepo: "epel,ol7_latest" - name: Install a list of packages yum: name: - nginx - postgresql - postgresql-server state: present - name: Download the nginx package but do not install it yum: name: - nginx state: latest download_only: true copy 选项 解释 参数 src 源路径 /root/http.conf.j2 dest 目标路径 /etc/httpd/conf/httpd.conf owner 属主 root group 属组 root mode 权限 644 backup 备份 yes content 写内容 hi,boy Examples - name: Copy file with owner and permissions copy: src: /srv/myfiles/foo.conf dest: /etc/foo.conf owner: foo group: foo mode: '0644' - name: Copy file with owner and permission, using symbolic representation copy: src: /srv/myfiles/foo.conf dest: /etc/foo.conf owner: foo group: foo mode: u=rw,g=r,o=r - name: Another symbolic mode example, adding some permissions and removing others copy: src: /srv/myfiles/foo.conf dest: /etc/foo.conf owner: foo group: foo mode: u+rw,g-wx,o-rwx - name: Copy a new "ntp.conf file into place, backing up the original if it differs from the copied version copy: src: /mine/ntp.conf dest: /etc/ntp.conf owner: root group: root mode: '0644' backup: yes - name: Copy a new "sudoers" file into place, after passing validation with visudo copy: src: /mine/sudoers dest: /etc/sudoers validate: /usr/sbin/visudo -csf %s - name: Copy a "sudoers" file on the remote machine for editing copy: src: /etc/sudoers dest: /etc/sudoers.edit remote_src: yes validate: /usr/sbin/visudo -csf %s - name: Copy using inline content copy: content: '# This file was moved to /etc/other.conf' dest: /etc/mine.conf - name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf copy: src: /etc/foo.conf dest: /path/to/link # link to /path/to/file follow: yes - name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf copy: src: /etc/foo.conf dest: /path/to/link # link to /path/to/file follow: no get_url 选项 解释 参数 url URL地址 dest 目标路径 checksum MD5校验 Examples - name: Download foo.conf get_url: url: http://example.com/path/file.conf dest: /etc/foo.conf mode: '0440' - name: Download file and force basic auth get_url: url: http://example.com/path/file.conf dest: /etc/foo.conf force_basic_auth: yes - name: Download file with custom HTTP headers get_url: url: http://example.com/path/file.conf dest: /etc/foo.conf headers: key1: one key2: two - name: Download file with check (sha256) get_url: url: http://example.com/path/file.conf dest: /etc/foo.conf checksum: sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c - name: Download file with check (md5) get_url: url: http://example.com/path/file.conf dest: /etc/foo.conf checksum: md5:66dffb5228a211e61d6d7ef4a86f5758 - name: Download file with checksum url (sha256) get_url: url: http://example.com/path/file.conf dest: /etc/foo.conf checksum: sha256:http://example.com/path/sha256sum.txt - name: Download file from a file path get_url: url: file:///tmp/afile.txt dest: /tmp/afilecopy.txt - name: < Fetch file that requires authentication. username/password only available since 2.8, in older versions you need to use url_username/url_password get_url: url: http://example.com/path/file.conf dest: /etc/foo.conf username: bar password: '{{ mysecret }}' file 选项 解释 参数 path 目标路径 /opt/centos state 状态 touch、directory owner 属主 root group 属组 root mode 权限 755 recurse 递归 yes Examples - name: Change file ownership, group and permissions file: path: /etc/foo.conf owner: foo group: foo mode: '0644' - name: Give insecure permissions to an existing file file: path: /work owner: root group: root mode: '1777' - name: Create a symbolic link file: src: /file/to/link/to dest: /path/to/symlink owner: foo group: foo state: link - name: Create two hard links file: src: '/tmp/{{ item.src }}' dest: '{{ item.dest }}' state: hard loop: - { src: x, dest: y } - { src: z, dest: k } - name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644) file: path: /etc/foo.conf state: touch mode: u=rw,g=r,o=r - name: Touch the same file, but add/remove some permissions file: path: /etc/foo.conf state: touch mode: u+rw,g-wx,o-rwx - name: Touch again the same file, but dont change times this makes the task idempotent file: path: /etc/foo.conf state: touch mode: u+rw,g-wx,o-rwx modification_time: preserve access_time: preserve - name: Create a directory if it does not exist file: path: /etc/some_directory state: directory mode: '0755' - name: Update modification and access time of given file file: path: /etc/some_file state: file modification_time: now access_time: now - name: Set access time based on seconds from epoch value file: path: /etc/another_file state: file access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}' - name: Recursively change ownership of a directory file: path: /etc/foo state: directory recurse: yes owner: foo group: foo - name: Remove file (delete file) file: path: /etc/foo.txt state: absent - name: Recursively remove directory file: path: /etc/foo state: absent service 选项 解释 参数 name 服务名 httpd state 状态 started、 enabled 开机自启 yes/no Examples - name: Start service httpd, if not started service: name: httpd state: started - name: Stop service httpd, if started service: name: httpd state: stopped - name: Restart service httpd, in all cases service: name: httpd state: restarted - name: Reload service httpd, in all cases service: name: httpd state: reloaded - name: Enable service httpd, and not touch the state service: name: httpd enabled: yes - name: Start service foo, based on running process /usr/bin/foo service: name: foo pattern: /usr/bin/foo state: started - name: Restart network service for interface eth0 service: name: network state: restarted args: eth0 group 选项 解释 参数 name 组名 youto gid GID 1234 state 状态 present、absent system 系统组 yes/no Examples- name: Ensure group "somegroup" exists group: name: somegroup state: present user 选项 解释 参数 name 用户名 acha uid UID 0527 group 用户组 root shell 解释器 /bin/bash、/sbin/nologin state 状态 present、absent create_home 创建家目录 yes/no remove 移除家目录 yes/no generate_ssh_key 创建密钥 yes/no ssh_key_bits 长度 2048 ssh_key_file 密钥位置 .ssh/id_rsa Examples - name: Add the user 'johnd' with a specific uid and a primary group of 'admin' user: name: johnd comment: John Doe uid: 1040 group: admin - name: Add the user 'james' with a bash shell, appending the group 'admins' and 'developers' to the user's groups user: name: james shell: /bin/bash groups: admins,developers append: yes - name: Remove the user 'johnd' user: name: johnd state: absent remove: yes - name: Create a 2048-bit SSH key for user jsmith in ~jsmith/.ssh/id_rsa user: name: jsmith generate_ssh_key: yes ssh_key_bits: 2048 ssh_key_file: .ssh/id_rsa - name: Added a consultant whose account you want to expire user: name: james18 shell: /bin/zsh groups: developers expires: 1422403387 - name: Starting at Ansible 2.6, modify user, remove expiry time user: name: james18 expires: -1 cron 选项 解释 参数 Examples - name: Ensure a job that runs at 2 and 5 exists. Creates an entry like "0 5,2 * * ls -alh > /dev/null" cron: name: "check dirs" minute: "0" hour: "5,2" job: "ls -alh > /dev/null" - name: 'Ensure an old job is no longer present. Removes any job that is prefixed by "#Ansible: an old job" from the crontab' cron: name: "an old job" state: absent - name: Creates an entry like "@reboot /some/job.sh" cron: name: "a job for reboot" special_time: reboot job: "/some/job.sh" - name: Creates an entry like "PATH=/opt/bin" on top of crontab cron: name: PATH env: yes job: /opt/bin - name: Creates an entry like "APP_HOME=/srv/app" and insert it after PATH declaration cron: name: APP_HOME env: yes job: /srv/app insertafter: PATH - name: Creates a cron file under /etc/cron.d cron: name: yum autoupdate weekday: "2" minute: "0" hour: "12" user: root job: "YUMINTERACTIVE=0 /usr/sbin/yum-autoupdate" cron_file: ansible_yum-autoupdate - name: Removes a cron file from under /etc/cron.d cron: name: "yum autoupdate" cron_file: ansible_yum-autoupdate state: absent - name: Removes "APP_HOME" environment variable from crontab cron: name: APP_HOME env: yes state: absent mount 选项 解释 参数 src 源路径 10.35.200.189:/data path 目标路径 /opt fstype 磁盘类型 nfs opts defaults state 状态 present、unmounted、mounted、absent Examples # Before 2.3, option 'name' was used instead of 'path' - name: Mount DVD read-only mount: path: /mnt/dvd src: /dev/sr0 fstype: iso9660 opts: ro,noauto state: present - name: Mount up device by label mount: path: /srv/disk src: LABEL=SOME_LABEL fstype: ext4 state: present - name: Mount up device by UUID mount: path: /home src: UUID=b3e48f45-f933-4c8e-a700-22a159ec9077 fstype: xfs opts: noatime state: present - name: Unmount a mounted volume mount: path: /tmp/mnt-pnt state: unmounted - name: Mount and bind a volume mount: path: /system/new_volume/boot src: /boot opts: bind state: mounted fstype: none selinux 选项 解释 参数 state 状态 enforcing、permissive、disabled Examples - name: Enable SELinux selinux: policy: targeted state: enforcing - name: Put SELinux in permissive mode, logging actions that would be blocked. selinux: policy: targeted state: permissive - name: Disable SELinux selinux: state: disabled firewalld 选项 解释 参数 service 服务名 httpd port 端口号 8080-9090 permanent 永久放行 yes immediate 临时放行 yes state 状态 enabled zone 区域 public Examples - firewalld: service: https permanent: yes state: enabled - firewalld: port: 8081/tcp permanent: yes state: disabled - firewalld: port: 161-162/udp permanent: yes state: enabled - firewalld: zone: dmz service: http permanent: yes state: enabled - firewalld: rich_rule: rule service name="ftp" audit limit value="1/m" accept permanent: yes state: enabled - firewalld: source: 192.0.2.0/24 zone: internal state: enabled - firewalld: zone: trusted interface: eth2 permanent: yes state: enabled - firewalld: masquerade: yes state: enabled permanent: yes zone: dmz - firewalld: zone: custom state: present permanent: yes - firewalld: zone: drop state: present permanent: yes icmp_block_inversion: yes - firewalld: zone: drop state: present permanent: yes icmp_block: echo-request - name: Redirect port 443 to 8443 with Rich Rule firewalld: rich_rule: rule family=ipv4 forward-port port=443 protocol=tcp to-port=8443 zone: public permanent: yes immediate: yes state: enabled ansible 变量 如何定义变量? play vars 定义变量 vars: - v1: value - v2: value - v3: value 使用变量 {{ v1 }} 实例 1、在playbook文件中的play使用变量 - hosts: oldboy vars: - web_packages: httpd-2.4.6 - ftp_packages: vsftpd-3.0.2 tasks: - name: Installed {{ web_packages }} {{ ftp_packages }} yum: name: - "{{ web_packages }}" - "{{ ftp_packages }}" state: present 2、通过定义一个变量文件,然后使用playbook进行调用 [root@m01 project1]# cat vars_public.yml web_packages: httpd-2.4.6 ftp_packages: vsftpd-3.0.2 [root@m01 project1]# cat vars_1.yml - hosts: oldboy vars_files: ./vars_public.yml tasks: - name: Installed {{ web_packages }} {{ ftp_packages }} yum: name: - "{{ web_packages }}" - "{{ ftp_packages }}" state: present 3、通过inventory主机清单进行变量定义 ## 在项目目录下创建两个变量的目录,host_vars group_vars #--------------------- group_vars ---------------- #1)在当前的项目目录中创建两个变量的目录 [root@ansible project1]# mkdir host_vars [root@ansible project1]# mkdir group_vars #2)在group_vars目录中创建一个文件,文件名与inventory清单中的组名称要保持完全一致。 [root@ansible project1]# cat group_vars/oldboy web_packages: wget ftp_packages: tree #3)编写playbook,只需在playbook文件中使用变量即可。 [root@ansible project1]# cat f4.yml - hosts: oldboy tasks: - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}" yum: name: - "{{ web_packages }}" - "{{ ftp_packages }}" state: present group_vars目录中文件名与hosts清单中的组名保持一致 系统提供了一个特殊组 all,在group_vars目录下建立一个all文件,所有组都可使用 #--------------------- hosts_vars ---------------- #1)在host_vars目录中创建一个文件,文件名与inventory清单中的主机名称要保持完全一致 [root@ansible project1]# cat hosts [oldboy] 172.16.1.7 172.16.1.8 #2)在host_vars目录中创建文件,给172.16.1.7主机定义变量 [root@ansible project1]# cat host_vars/172.16.1.7 web_packages: zlib-static ftp_packages: zmap #3)准备一个playbook文件调用host主机变量 [root@ansible project1]# cat f4.yml - hosts: 172.16.1.7 tasks: - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}" yum: name: - "{{ web_packages }}" - "{{ ftp_packages }}" state: present - hosts: 172.16.1.8 tasks: - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}" yum: name: - "{{ web_packages }}" - "{{ ftp_packages }}" state: present 4、通过执行playbook时使用-e参数指定变量 [root@m01 project1]# cat vars_7.yml - hosts: "{{ hosts }}" #注意:这是一个变量名称 tasks: - name: Install Rpm Packages "{{ web_packages }}" "{{ ftp_packages }}" yum: name: - "{{ web_packages }}" - "{{ ftp_packages }}" state: present [root@m01 project1]# #ansible-playbook -i hosts vars_7.yml -e "hosts=oldboy" 变量优先级 1. 外置传参 2. playbook(vars_files-->vars) 3. inventory(host_vars-->group_vars/group_name-->group_vars-all) 变量注册 register debug [root@m01 project1]# cat vars_9.yml - hosts: oldboy tasks: - name: Installed Httpd Server yum: name=httpd state=present - name: Service Httpd Server service: name=httpd state=started - name: Check Httpd Server shell: ps aux|grep httpd register: check_httpd - name: OutPut Variables debug: msg: "{{ check_httpd.stdout_lines }}" facts变量 用来采集被控端的状态指标,比如: IP地址 、主机名称 、cpu信息、内存 等等 采集被控端的信息,赋值到facts变量 查看 face变量 # 将变量保存到 文本里 ansible 172.16.1.8 -m setup -i hosts > face.txt # 查询备控端内存大小 ansible 172.16.1.8 -m setup -a "filter=ansible_memtotal_mb" -i hosts memcache - hosts: oldboy tasks: - name: Installed Memcached Server yum: name=memcached state=present - name: Configure Memcached Server template: src=./memcached.j2 dest=/etc/sysconfig/memcached - name: Service Memcached Server service: name=memcached state=started enabled=yes - name: Check Memcached Server shell: ps aux|grep memcached register: check_mem - name: Debug Memcached Variables debug: msg: "{{ check_mem.stdout_lines }}" task 控制 概述 1. 判断语句 when 根据主机名称来安装不同的yum仓库 根据主机的系统安装不同的软件包 2. 循环语句 with_items: 列表 item 基本循环 字典循环 facts 3. handlers触发 notify 通知 handlers 执行 4. include include tasks include_tasks tasks import_playbook playbook 5. tags标签 调试模式使用 -t 指定 --skip-tags: 跳过 6. 忽略错误ignore_errors: yes 7. 错误处理 fource_handlers: yes 强制调用handlers(少) change_when: false 抑制changed状态 change_when: (check_nginx.stdout.find('ok') 实例 1、条件判断 when 根据不同操作系统,安装相同的软件包 - hosts: oldboy tasks: - name: Installed {{ ansible_distribution }} Httpd Server yum: name=httpd state=present when: ( ansible_distribution == "CentOS" ) - name: Installed {{ ansible_distribution }} Httpd2 Server yum: name=httpd2 state=present when: ( ansible_distribution == "Ubuntu" ) 为所有的web主机名添加nginx仓库,其余的都跳过添加 - hosts: all tasks: - name: Create YUM Repo yum_repository: name: ansible_nginx description: ansible_test baseurl: https://mirrors.oldboy.com gpgcheck: no enabled: no when: ( ansible_fqdn is match ("web*")) 根据命令执行的结果进行判断 - hosts: all tasks: #检查httpd服务是否是活动的 - name: Check Httpd Server command: systemctl is-active httpd ignore_errors: yes register: check_httpd #如果check_httpd变量中的rc结果等于0,则执行重启httpd,否则跳过 - name: Httpd Restart service: name=httpd state=restarted when: check_httpd.rc == 0 2、循环语句 with_items 使用循环启动多个服务 - hosts: webserver tasks: - name: Service Nginx Server service: name={{ item }} state=restarted with_items: - nginx - php-fpm 定义变量方式循环安装软件包 - hosts: web tasks: - name: Installed Httpd Mariadb Package yum: name={{ pack }} state=latest vars: pack: - httpd - mariadb-server - hosts: webserver tasks: - name: Installed Httpd Mariadb Package yum: name={{ pack }} state=latest vars: pack: - httpd - mariadb-server 使用变量字典循环方式批量创建用户 [root@m01 project1]# cat tasks_6.yml - hosts: webserver tasks: - name: Create User user: name={{ item.name }} groups={{ item.groups }} state=present with_items: - { name: 'www', groups: 'bin'} - { name: 'test', groups: 'root'} 3、handlers 触发器 httpd 更改配置重启服务 - hosts: webserver #1.定义变量,在配置文件中调用 vars: http_port: 8881 #2.安装httpd服务 tasks: - name: Install Httpd Server yum: name=httpd state=present #3.使用template模板,引用上面vars定义的变量至配置文件中 - name: Configure Httpd Server template: src=./httpd.conf dest=/etc/httpd/conf/httpd.conf notify: #调用名称为Restart Httpd Server的handlers(可以写多个) - Restart Httpd Server #4.启动Httpd服务 - name: Start Httpd Server service: name=httpd state=started enabled=yes #5.如果配置文件发生变化会调用该handlers下面的对应名称的task handlers: - name: Restart Httpd Server service: name=httpd state=restarted handlers注意事项 handlers仅会在所有tasks结束后运行一次 只有task发生改变了才会通知handlers触发 handlers是一个特殊的tasks 4、tags标签 打标签 对一个tasks指定一个tags标签 对一个tasks指定多个tags标签 多个tasks任务指定一个tags标签 指定执行某个tags标签 ansible-playbook -i hosts nginx_php.yml -t "test_user" 忽略执行某个tags标签 ansible-playbook -i hosts nginx_php.yml --skip-tags "test_user" 示例 - hosts: webserver tasks: - name: Install Nfs Server yum: name=nfs-utils state=present tags: install_nfs - name: Service Nfs Server service: name=nfs-server state=started enabled=yes tags: start_nfs-server 5、include包含 1)编写restart_httpd.yml文件 [root@ansible project1]# cat restart_httpd.yml # 注意这是一个tasks所有没有play的任何信息 - name: Restart Httpd Server service: name=httpd state=restarted 2)A Project的playbook如下 [root@ansible project1]# cat a_project.yml - hosts: webserver tasks: - name: A Project command command: echo "A" - name: Restart httpd include: restart_httpd.yml 3)B Project的playbook如下 [root@ansible project1]# cat b_project.yml - hosts: webserver tasks: - name: B Project command command: echo "B" - name: Restart httpd include_tasks: restart_httpd.yml 导入一个完整的playbook文件 (play task) [root@m01 project1]# cat tasks_total.yml - import_playbook: ./tasks_1.yml - import_playbook: ./tasks_2.yml 6、错误忽略ignore_errors ignore_errors: yes - hosts: webserver tasks: - name: Command command: /bin/false ignore_errors: yes - name: Create File file: path=/tmp/tttt state=touch 7、错误处理changed_when 强制调用handlers - hosts: webserver # 强制调用handlers force_handlers: yes tasks: - name: Touch File file: path=/tmp/bgx_handlers state=touch notify: Restart Httpd Server - name: Installed Packages yum: name=sb state=latest handlers: - name: Restart Httpd Server service: name=httpd state=restarted 关闭changed的状态 - hosts: webserver tasks: - name: Installed Httpd Server yum: name=httpd state=present - name: Service Httpd Server service: name=httpd state=started - name: Check Httpd Server shell: ps aux|grep httpd register: check_httpd changed_when: false - name: OutPut Variables debug: msg: "{{ check_httpd.stdout_lines }}" 使用hanged_when检查tasks任务返回的结果 - hosts: webserver tasks: - name: Installed Nginx Server yum: name=nginx state=present - name: Configure Nginx Server copy: src=./nginx.conf.j2 dest=/etc/nginx/nginx.conf notify: Restart Nginx Server - name: Check Nginx Configure Status command: /usr/sbin/nginx -t register: check_nginx changed_when: - ( check_nginx.stdout.find('successful')) - false - name: Service Nginx Server service: name=nginx state=started handlers: - name: Restart Nginx Server service: name=nginx state=restarted lnmp - hosts: webserver tasks: - name: Installed Nginx PHP-FPM Server yum: name={{ packages }} state=present vars: packages: - nginx - php - php-fpm - php-cli - php-pdo - php-mbstring - php-gd - name: Create Nginx Group {{ web_user }} group: name={{ web_user }} gid=666 state=present - name: Create Nginx User {{ web_user }} user: name={{ web_user }} uid=666 group={{ web_user }} state=present - name: Create Kod {{ kod_server_path }} Directory file: path={{ kod_server_path }} state=directory - name: Unzip Kod {{ kod_server_path }} Directory unarchive: src=./playbook/kodexplorer4.40.zip dest={{ kod_server_path }} - name: Chown Kod Data {{ web_user }} file: path={{ kod_server_path }} owner={{ web_user }} group={{ web_user }} recurse=yes mode=0777 - name: Configure Nginx Server template: src={{ item.src }} dest={{ item.dest }} backup=yes with_items: - {src: './nginx.conf.j2',dest: '/etc/nginx/nginx.conf'} - {src: './kod.conf.j2',dest: '/etc/nginx/conf.d/kod.conf'} notify: Restart Nginx Server - name: Check Nginx Server shell: /usr/sbin/nginx -t register: check_nginx changed_when: - ( check_nginx.stdout.find('successful')) - false - name: Configure PHP-FPM Server template: src={{ item.src }} dest={{ item.dest }} backup=yes with_items: - {src: './php.ini.j2',dest: '/etc/php.ini'} - {src: './php_www.conf.j2',dest: '/etc/php-fpm.d/www.conf'} notify: Restart PHP-FPM Server - name: Check PHP-FPM Server shell: /usr/sbin/php-fpm -t register: check_phpfpm changed_when: - ( check_phpfpm.stdout.find('successful')) - false - name: Start Nginx PHP Server service: name={{ item }} state=started enabled=yes with_items: - nginx - php-fpm handlers: - name: Restart Nginx Server service: name=nginx state=restarted - name: Restart PHP-FPM Server service: name=php-fpm state=restarted [root@m01 project1]# cat group_vars/all #nginx php variables web_user: www nginx_conf: /etc/nginx/nginx.conf nginx_virt: /etc/nginx/conf.d nginx_code: /ansible_code server_port: 80 kod_server_name: kod.oldboy.com kod_server_path: /nginx_code ### php_fpm_conf: /etc/php-fpm.d/www.conf php_ini_conf: /etc/php.ini php_ini_max_upload: 200M jinja2 {% if EXPR %}...{% elif EXPR %}...{% endif%} 作为条件判断 {% for i in EXPR %}...{% endfor%} 作为循环表达式 {# COMMENT #} 表示注释 jinja实现keepalived [root@m01 project1]# cat keepalived.conf.j2 global_defs { router_id {{ ansible_fqdn }} } vrrp_instance VI_1 { {% if ansible_fqdn == "lb01" %} state MASTER priority 150 {% elif ansible_fqdn == "lb02" %} state BACKUP priority 100 {% endif %} ###------------------相同点 interface eth0 virtual_router_id 50 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 10.0.0.3 } } roles Roles基于一个已知的文件结构 tasks handlers templates ..... Roles小技巧: 创建roles目录结构,手动或使用ansible-galaxy init test roles 编写roles的功能,也就是tasks 最后playbook引用roles编写好的tasks [root@m01 project2]# mkdir memcached/{tasks,handlers,templates,vars,files} -pv mkdir: 已创建目录 "memcached" mkdir: 已创建目录 "memcached/tasks" mkdir: 已创建目录 "memcached/handlers" mkdir: 已创建目录 "memcached/templates" mkdir: 已创建目录 "memcached/vars" mkdir: 已创建目录 "memcached/files" [root@m01 project2]# mkdir {nginx,php-fpm}/{tasks,handlers,templates} -p galaxy 注:笔记整理自徐亮伟老师的笔记与视频
2021年07月16日
236 阅读
0 评论
2 点赞
1
2
3
4
...
6