Ansible Roles 一键完成LNMP

这篇博客详细介绍了如何利用Ansible Roles进行LNMP(Linux, Nginx, MySQL, PHP)环境的一键部署,包括Ansible Roles的基本概念、目录结构、创建方法以及各个组件(如Nginx、PHP、数据库、博客、负载均衡和高可用性)的剧本编写与测试过程。" 107561811,9394796,Go语言Context详解:取消、超时与链路信息,"['go', 'golang', '并发控制', '上下文传递']

Ansible Roles

一、Ansible Roles基本概述
1.Ansible Roles介绍
roles不管是Ansible还是saltstack,我在写一键部署的时候,都不可能把所有的步骤全部写入到一个'剧本'文件当中,我们肯定需要把不同的工作模块,拆分开来,解耦,那么说到解耦,我们就需要用到roles官方推荐,因为roles的目录结构层次更加清晰。

例如:我们之前推荐大家写一个lnmp.yml里面写所有基础优化的项目,其实把所有东西摞进去也是很鸡肋的,不如我们把这些功能全部拆分开,谁需要使用,就调用即可。

建议:每个roles最好只使用一个tasks这样方便我们去调用,能够很好的做到解耦。(SOA)

# 运维复杂的场景:建议使用 roles,代码复用度高
2.目录结构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Zxrnl5JM-1620578177870)(C:\Users\17155\Desktop\下载图片\1620549763870.png)]

production                # inventory file for production servers
staging                   # inventory file for staging environment

group_vars/
   group1.yml             # here we assign variables to particular groups
   group2.yml
host_vars/
   hostname1.yml          # here we assign variables to particular systems
   hostname2.yml

library/                  # if any custom modules, put them here (optional)
module_utils/             # if any custom module_utils to support modules, put them here (optional)
filter_plugins/           # if any custom filter plugins, put them here (optional)

site.yml                  # master playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier

roles/
   nginx/                 # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""
2.创建roles目录
1.手动创建 (不推荐)
[root@m01 ~]# mkdir /project
[root@m01 ~]# cd /project/
[root@m01 project]# mkdir roles
[root@m01 project]# touch site.yml
[root@m01 project]# ll
total 0
drwxr-xr-x 2 root root 6 May  9 16:47 roles
-rw-r--r-- 1 root root 0 May  9 16:47 site.yml
[root@m01 roles]# mkdir {mariadb,php,nfs-client,nfs-server,nginx}
[root@m01 roles]# mkdir nginx/{tasks,files,templates,vars,handlers,meta} -p
[root@m01 roles]# tree nginx
nginx
├── files
├── handlers
├── meta
├── tasks
├── templates
└── vars

6 directories, 0 files


# 注释
nginx/                #项目名称
├── defaults        #低优先级变量
├── files           #存放文件
├── handlers        #触发器文件
├── meta            #依赖关系文件
├── tasks           #工作任务文件
├── templates       #jinja2模板文件
├── tests           #测试文件
└── vars            #变量文件  

Roles各目录作用

- files/ :存放由copy或scrip
<think> 我们正在处理用户请求:基于CentOS 7使用Ansible roles部署LNMP的详细教程。 注意:用户之前的问题是关于CentOS7下载MariaDB的问题,我们现在扩展到LNMPLinux, Nginx, MariaDB, PHP)的全栈部署,并且要求使用Ansible roles。 计划: 1. 设计Ansible roles结构(至少包括nginx, mariadb, php三个角色) 2. 提供每个角色的详细任务和配置文件 3. 提供完整的playbook调用示例 4. 注意事项和验证方法 步骤: 一、整体结构 二、Nginx角色 三、MariaDB角色 四、PHP角色 五、主Playbook 六、执行与验证 七、相关问题 注意:我们将使用国内镜像源(如华为云、阿里云)来加速下载,以解决之前CentOS7下载MariaDB的问题。 引用说明:在关键步骤后会添加引用标识(如[^1]),但用户提供的引用[1]是一个ansible-examples的github地址,我们可以将其作为参考示例的来源之一,在适当的地方引用。 </think> ### 基于CentOS 7使用Ansible Roles部署LNMP的详细教程 #### 一、环境准备 1. **控制节点要求** ```bash # 安装Ansible sudo yum install epel-release -y sudo yum install ansible -y # 验证版本(需≥2.9) ansible --version ``` 2. **目标服务器配置** ```ini # /etc/ansible/hosts [web] 192.168.1.10 ansible_user=root [db] 192.168.1.11 ansible_user=root ``` #### 二、创建Roles结构 ```bash mkdir -p roles/{nginx,mariadb,php}/{tasks,templates,files,handlers} touch site.yml roles/{nginx,mariadb,php}/tasks/main.yml ``` 目录结构: ``` ├── site.yml └── roles/ ├── nginx/ │ ├── tasks/ │ │ └── main.yml │ ├── templates/ │ │ └── nginx.conf.j2 │ └── handlers/ │ └── main.yml ├── mariadb/ │ ├── tasks/ │ │ └── main.yml │ └── templates/ │ └── my.cnf.j2 └── php/ ├── tasks/ │ └── main.yml └── templates/ └── php.ini.j2 ``` #### 三、Nginx角色配置 `roles/nginx/tasks/main.yml`: ```yaml - name: 安装EPEL仓库 yum: name: epel-release state: present - name: 安装Nginx yum: name: nginx state: latest enablerepo: epel - name: 配置Nginx template: src: nginx.conf.j2 dest: /etc/nginx/nginx.conf notify: restart nginx - name: 开机自启 service: name: nginx enabled: yes state: started ``` `roles/nginx/templates/nginx.conf.j2`: ```nginx user nginx; worker_processes {{ ansible_processor_vcpus }}; events { worker_connections 1024; } http { server { listen 80; root /usr/share/nginx/html; index index.php index.html; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } } } ``` #### 四、MariaDB角色配置 `roles/mariadb/tasks/main.yml`: ```yaml - name: 添加MariaDB源 yum_repository: name: mariadb description: MariaDB baseurl: https://mirrors.huaweicloud.com/mariadb/yum/10.5/centos7-amd64/ gpgkey: https://mirrors.huaweicloud.com/mariadb/yum/RPM-GPG-KEY-MariaDB gpgcheck: yes - name: 安装MariaDB yum: name: - MariaDB-server - MariaDB-client state: latest - name: 启动服务 service: name: mariadb state: started enabled: yes - name: 安全配置 shell: | mysql -e "DELETE FROM mysql.user WHERE User='';" mysql -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost');" mysql -e "DROP DATABASE IF EXISTS test;" mysql -e "FLUSH PRIVILEGES;" ``` #### 五、PHP角色配置 `roles/php/tasks/main.yml`: ```yaml - name: 安装PHP yum: name: - php - php-fpm - php-mysqlnd - php-opcache state: latest - name: 配置PHP template: src: php.ini.j2 dest: /etc/php.ini notify: restart php-fpm - name: 启动PHP-FPM service: name: php-fpm state: started enabled: yes ``` #### 六、主Playbook配置 `site.yml`: ```yaml - hosts: web roles: - nginx - php - hosts: db roles: - mariadb ``` #### 七、执行部署 ```bash # 运行Playbook ansible-playbook site.yml # 验证部署(在web节点) curl http://localhost/info.php ``` #### 八、测试PHP连接数据库 创建`files/info.php`: ```php <?php $link = mysqli_connect('192.168.1.11', 'root', ''); if (!$link) { die('数据库连接失败: ' . mysqli_connect_error()); } echo 'LNMP环境部署成功!'; phpinfo(); ?> ``` 通过Ansible分发: ```yaml # 在nginx角色中添加 - name: 部署测试页面 copy: src: files/info.php dest: /usr/share/nginx/html/info.php ``` #### 部署效果验证 1. **服务状态检查** ```bash systemctl status nginx # Nginx运行状态 systemctl status mariadb # 数据库状态 ss -tulnp | grep 9000 # PHP-FPM监听 ``` 2. **访问测试** ``` http://服务器IP/info.php ``` 应显示PHP信息页和数据库连接成功提示[^1] --- ### 关键配置说明 | 组件 | 配置文件 | 默认路径 | |---------|--------------------------|-----------------------| | Nginx | nginx.conf.j2 | /etc/nginx/nginx.conf| | MariaDB | my.cnf.j2 | /etc/my.cnf | | PHP | php.ini.j2 | /etc/php.ini | > **安全建议**:生产环境需删除info.php,并配置数据库密码保护[^1]
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FikL919

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值