Python-Fabric自动化工具-部署LNMP架构(最新,最全)

Python-Fabric自动化工具-部署LNMP架构(最新,最全)

fabric介绍
Fabric是一个高级Python(2.7-3.4+)的库和命令行工具,用来提高基于SSH的应用部署和系统管理效率.
更具体的说,Fabric是:
	1.一个让你通过命令行执行无阐述python函数的工具;
	2.一个让通过SSH执行shell命令更加容易,更符合python风格的命令库,(建立于一个更低层次的库)
自然而然的,大部分用户把这两件事结合着用,使用Fabric来写和执行Python函数或task,以实现与远程服务器的自动化交互.
官方文档:https://docs.fabfile.org/en/2.6/getting-started.html#a-note-about-imports
fabric下载安装
下载Python
#下载python
apt-get install python 或者 yum -y install python
#下载pip
apt install pip	或者 yum -y install python
#查看python+pip的版本
python -V
pip -V
安装virtualenv虚拟化
#安装virtualenv虚拟化
pip install virtualenv
mkdir py && cd py/
#创建虚拟化环境
virtualenv py
#激活虚拟化环境
source py/bin/activate
#包检测
pip freeze
#退出虚拟化环境
deactivate 
下载安装fabric
#下载并安装fabric
pip install fabric fabric3
pip freeze
#查看fabric的版本
fab -V
使用python查看能调用那些fabric的变量
(py) root@hy:/home/hy/py# python
Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fabric
>>> dir(fabric)
['Config', 'Connection', 'Executor', 'Group', 'GroupResult', 'Remote', 'Result', 'SerialGroup', 'Task', 'ThreadingGroup', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '__version_info__', '_version', 'config', 'connection', 'exceptions', 'executor', 'group', 'runners', 'task', 'tasks', 'transfer', 'tunnels', 'util']
>>> exit()
fabric选项参数
参数项含义
-I显示定义好的任务函数列表
-f指定fab入口文件,默认入口文件名为fabfile.py
-g指定网关
-H指定目标主机,多个主机用","隔开
-P以异步并行方式运行多主机任务,默认为串行任务
-R指定角色(Role)
-u指定主机用户名
-p指定主机密码
-t设置设备连接超时时间
-T设置远程主机命令执行超时时间
-w当命令执行失败,发出告警,而非默认终止任务
编写fabfile
属性含义格式
env.hosts定义多个目标主机env.hosts=[“10.0.0.4”,“10.0.0.5”]
env.user定义用户名env.user = “root”
env.port定义端口env.port = 22
env.password定义密码env.password = 1
env.passwords定义多台主机的用户名,IP地址,端口,密码env.passwords = {
“root@10.0.0.4:22”:“1”,
}
env.gateway定义网关env.gateway = “10.0.0.2”
env.roledefs定义角色分组ren.roledefs = {
“webservers”:[“10.0.0.4”,“10.0.0.5”] “dbservers”:[“10.0.0.6”,“10.0.0.7”]}
env.exclide_hosts排除指定主机,以python的列表表示
env.deploy_release_dir自定义全局变量
本地与远程运维常用API
方法说明
local执行本地命令,如:local(‘hostname’)
lcd切换本地目录,lcd(’/root’)
cd切换远程目录,cd(‘cd’)
run执行远程命令,如:run(‘hostname’)
sudosudo执行远程命令,如:sudo('echo “123456″)
put上传本地文件到远程主机,如:put(src,des)
get从远程主机下载文件到本地,如:get(des,src)
prompt获取用户输入信息,如:prompt(‘please enter a new password:’)
confirm获取提示信息确认,如:confirm(‘failed.Continue[Y/n]?’)
reboot重启远程主机,reboot()
@task函数修饰符,标识的函数为fab可调用的
@runs_once函数修饰符,表示的函数只会执行一次
输出颜色
#输出颜色
from fabric.colors import *		#使用fabric.colors库
颜色输入
黄色yellow(“hello world”)
蓝色blue(“hello world”)
红色red(“hello world”)
绿色green(“hello world”)
青色cyan(“hello world”)
紫色magenta(“hello world”)
白色white(“hello world”)
多主机批量并行运维
#基本操作
1.指定多台主机IP或域名
env.hosts = ["10.0.0.x","10.0.0.xx","10.0.0.xxx",...]
2.指定多台主机的密码
env.passwords = {
	"root@10.0.0.x:22":"root",
	"root@10.0.0.xx:22":"root",
	"root@10.0.0.xxx:22":"root",
	...
}
3.指定主机角色分组
env.roledefs = {
	"xxx1":["10.0.0.x","10.0.0.xx","10.0.0.xxx",...],
	"xxx2":["10.0.0.x","10.0.0.xx","10.0.0.xxx",...],
}
4.并行装饰器:@parallel

5.角色装饰器:@roles(角色)

6.主机装饰器:@hosts(主机1,主机2)
centos7多主机部署-LNMP(Linux+Nginx+MySQL+PHP)
服务器准备
主机名称操作系统IP地址主要程序
win10管理机windows 1010.0.0.1Python.Fabric
web01服务器CentOS 7.610.0.0.13LNMP
web02服务器CentOS 7.610.0.0.14LNMP
Fabfile
# -*- codeing = utf-8 -*-
# @Time : 2021/6/30 下午 02:49
# @Author : 霍義
# @File : fabric-lnmp.py
# @Software : PyCharm
from fabric.api import *

env.hosts = ["10.0.0.13", "10.0.0.14"]
env.user = "root"
env.passwords = {
    "root@10.0.0.13:22":"1",
    "root@10.0.0.14:22":"1"
}

@task
def php_install():
    a = """[php-webtatic]\nname = PHP Repository\nbaseurl = http://us-east.repo.webtatic.com/yum/el7/x86_64/\ngpgcheck = 0"""
    run("echo '%s' > /etc/yum.repos.d/php.repo" % a)
    run("yum -y install php72w php72w-cli php72w-fpm php72w-common php72w-devel php72w-embedded php72w-gd php72w-mbstring php72w-mysqlnd php72w-opcache php72w-pdo php72w-xml")

@task
def php_start():
    run("systemctl start php-fpm")
    run("systemctl enable php-fpm")
    run("systemctl status php-fpm")
    run("netstat -tnulp | grep 9000")

@task
def nginx_install():
    ng = """[nginx-stable]\nname=nginx stable repo\nbaseurl=http://nginx.org/packages/centos/$releasever/$basearch/\ngpgcheck=1\nenabled=1\ngpgkey=https://nginx.org/keys/nginx_signing.key\nmodule_hotfixes=true"""
    run("echo '%s' > /etc/yum.repos.d/nginx.repo" % ng)
    run("yum -y install nginx")

@task
def nginx_start():
    run("nginx -t")
    run("systemctl start nginx")
    run("systemctl enable nginx")
    run("systemctl status nginx")
    run("netstat -tnulp | grep 80")

@task
def mariadb_install():
    run("yum -y install mariadb-server")

@task
def mariadb_start():
    run("systemctl start mariadb")
    run("systemctl enable mariadb")
    run("systemctl status mariadb")
    run("netstat -tnulp | grep 3306")

#此段需要手动执行一下.本人Python也是刚学,所以还不太熟练."0.0"
@task
def mariadb_password():
    run("mysqladmin -uroot -p password 123456")
	
@task
def mariadb_create():
    run("mysql -uroot -p123456 -e 'create database wordpress;'")
    run("mysql -uroot -p123456 -e 'show databases;'")
    run("systemctl status mariadb")
    run("netstat -tnulp | grep 3306")

@task
def nginx_server():
    b = """
server {
    listen 80;
    server_name localhosts;
    root /code/wordpress;
    index index.php index.html;

    location ~ \.php$ {
        root /code/wordpress;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
    """
    run("mkdir /code -p")
    run("echo '%s' >> /etc/nginx/conf.d/wordpress.conf" % b)

@task
def rz_wordpress():
    put("wordpress-5.0.3-zh_CN.tar.gz", "/opt/wordpress-5.0.3-zh_CN.tar.gz")
    run("tar xf /opt/wordpress-5.0.3-zh_CN.tar.gz -C /code/")

@task
def chmod_chown():
    run("chmod -R 755 /code")
    run("chmod -R 755 /etc/nginx/conf.d/wordpress.conf")
    run("chown -R root.root /code")

@task
def version_server():
    run("mysql --version")
    run("php -v")
    run("nginx -V")
    run("netstat -tnulp")

@task
def curl_I():
    run("curl -I 10.0.0.13")
    run("curl -I 10.0.0.14")

def run_all():
    execute(php_install)
    execute(php_start)
    execute(nginx_install)
    execute(nginx_start)
    execute(mariadb_install)
    execute(mariadb_start)
    execute(mariadb_password)
    execute(mariadb_create)
    execute(nginx_server)
    execute(rz_wordpress)
    execute(chmod_chown)
    execute(version_server)
    execute(curl_I)

if __name__ == "__main__":
    run_all()

在这里插入图片描述
编写不易,各位小伙伴记得点赞、评论,最后祝君在新的一年中好运爆棚~~~

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 安装ansible 在一台主控机上安装ansible,并将需要部署的目标机器的IP地址加入到ansible的hosts文件中。 2. 编写playbook 使用yaml格式编写ansible playbook文件,包括以下任务: - 安装Nginx、MySQL和PHP - 修改Nginx配置文件,配置虚拟主机和反向代理 - 修改MySQL配置文件,设置root密码和字符集 - 部署PHP应用程序文件和配置文件 示例playbook文件如下: ```yaml --- - hosts: webservers become: true tasks: - name: Install packages yum: name: "{{ item }}" state: present with_items: - nginx - mysql - mysql-server - php - php-mysql - php-fpm - name: Start services service: name: "{{ item }}" state: started enabled: true with_items: - nginx - mysqld - php-fpm - name: Configure Nginx copy: src: files/nginx.conf dest: /etc/nginx/nginx.conf notify: - Reload Nginx - name: Configure MySQL copy: src: files/my.cnf dest: /etc/my.cnf notify: - Restart MySQL - name: Deploy PHP application copy: src: files/php_app dest: /usr/share/nginx/html - name: Configure PHP copy: src: files/php.ini dest: /etc/php.ini notify: - Restart PHP-FPM handlers: - name: Reload Nginx service: name: nginx state: reloaded - name: Restart MySQL service: name: mysqld state: restarted - name: Restart PHP-FPM service: name: php-fpm state: restarted ``` 3. 准备文件 将需要部署的应用程序文件和配置文件打包成tar.gz文件,并放置在主控机上。 4. 执行playbook 在主控机上执行ansible-playbook命令,指定playbook文件和目标机器的IP地址,以及需要部署的应用程序文件和配置文件的路径。 ```bash ansible-playbook -i hosts playbook.yml --extra-vars "app_file=/path/to/app.tar.gz" ``` 5. 验证部署 访问Nginx的虚拟主机地址,验证应用程序是否正常运行。同时,使用MySQL客户端连接数据库,验证数据库是否正常运行并包含正确的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值