Ansible分离部署LAMP

Ansible分离部署LAMP

实验环境

主机ip系统平台
ansible192.168.229.152centos8/redhat8
apache192.168.229.148centos8/redhat8
mysql192.168.229.150centos8/redhat8
php192.168.229.151centos8/redhat8

lamp平台软件安装次序:

    httpd --> mysql --> php

注意:php要求httpd使用prefork MPM

ansible配置国内源

[root@ansible ~]# cd /etc/yum.repos.d/
[root@ansible yum.repos.d]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
[root@localhost yum.repos.d]# sed -i -e '/mirrors.cloud.aliyuncs.com/d' -e '/mirrors.aliyuncs.com/d' /etc/yum.repos.d/CentOS-Base.repo
#清除缓存
[root@ansible yum.repos.d]# dnf clean all
#建立缓存
[root@ansible yum.repos.d]# dnf makecache

安装ansible

#列出ansible
[root@ansible ~]# dnf list all|grep ansible
....省略N
ansible-pcp.noarch                 2.2.1-1.el8  AppStream 
centos-release-ansible-29.noarch   1-2.el8      extras #需要这个安装Ansible源
....省略N

#安装ansible源
[root@ansible ~]# dnf -y install centos-release-ansible-29
#清除缓存
[root@ansible ~]# dnf clean all
#建立缓存
[root@ansible ~]# dnf makecache

# 安装ansible
[root@ansible ~]# dnf -y install ansible
.....安装过程省略N

设置域名

[root@ansible ~]# vim /etc/hosts

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.229.148 apache.example.com
192.168.229.150 database
192.168.229.151 php.example.com

设置免密登录

# 设置免密登录
## 生成密钥(将会生成私钥~/.ssh/id_rsa和公钥~/.ssh/id_rsa.pub)
[root@ansible ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
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:LFrLpOXE8a2ohWyv4Mds+ydm0avqn2eUrIPHf8M4HnM root@ansible
The key's randomart image is:
+---[RSA 3072]----+
|                 |
|                 |
|      .          |
|     . + .       |
|      BoS..      |
|   . @.+=.       |
|  .o*o*+++E      |
| . o*+O.B++      |
|  .+*X*Xoo .     |
+----[SHA256]-----+

[root@ansible ~]# ls .ssh
id_rsa  id_rsa.pub


# 使用 ssh-copy-id 将公钥复制到apache上的正确位置
[root@ansible ~]# ssh-copy-id root@apache.example.com
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'apache.example.com (192.168.229.148)' can't be established.
ECDSA key fingerprint is SHA256:n2ckGGr820b4Fez6NUHXuOApoQ3oCuf3POTLfTxOsS4.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes //输入yes
/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
root@apache.example.com's password:  # 输入密码

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@apache.example.com'"
and check to make sure that only the key(s) you wanted were added.

#登录到apache主机并修改主机名
[root@ansible ~]# ssh root@apache.example.com
Last login: Sat Jul 30 10:22:24 2022 from 192.168.229.1
[root@localhost ~]# ip addr show ens160
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:57:8f:93 brd ff:ff:ff:ff:ff:ff
    inet 192.168.229.148/24 brd 192.168.229.255 scope global dynamic noprefixroute ens160
       valid_lft 1512sec preferred_lft 1512sec
    inet6 fe80::20c:29ff:fe57:8f93/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

[root@localhost ~]# hostnamectl set-hostname apache
[root@localhost ~]# bash
[root@apache ~]# exit # 退出
exit
[root@localhost ~]# exit

# 将公钥传到mysql主机
[root@ansible ~]# ssh-copy-id root@database
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'database (192.168.229.150)' can't be established.
ECDSA key fingerprint is SHA256:BSCsrBDXmOy0vQCzkxthvFwA+8EIkoMVyeVV45QrFdM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/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
root@database's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@database'"
and check to make sure that only the key(s) you wanted were added.

#登录到mysql主机并修改主机名
[root@ansible ~]# ssh root@database
Last login: Sun Jul 31 10:22:24 2022 from 192.168.229.1
[root@localhost ~]# ip addr show ens160
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:c7:d2:c9 brd ff:ff:ff:ff:ff:ff
    inet 192.168.229.150/24 brd 192.168.229.255 scope global dynamic noprefixroute ens160
       valid_lft 1099sec preferred_lft 1099sec
    inet6 fe80::20c:29ff:fec7:d2c9/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
[root@localhost ~]# hostnamectl set-hostname mysql
[root@localhost ~]# bash
[root@mysql ~]# exit
exit
[root@localhost ~]# exit
logout
Connection to database closed.
[root@ansible ~]#

#将公钥传到PHP主机
[root@ansible ~]# ssh-copy-id root@php.example.com
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
The authenticity of host 'php.example.com (192.168.229.151)' can't be established.
ECDSA key fingerprint is SHA256:8hpIIROKg7YiNUKNVhMqXp6yhUetFbsglx+JETkaZXo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/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
root@php.example.com's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@php.example.com'"
and check to make sure that only the key(s) you wanted were added.


#登录到php主机并修改主机名
[root@ansible ~]# ssh root@php.example.com
Last login: Sat Jul 30 10:22:26 2022 from 192.168.229.1
[root@localhost ~]# ip addr show ens160
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:0c:29:32:af:6d brd ff:ff:ff:ff:ff:ff
    inet 192.168.229.151/24 brd 192.168.229.255 scope global dynamic noprefixroute ens160
       valid_lft 977sec preferred_lft 977sec
    inet6 fe80::20c:29ff:fe32:af6d/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
[root@localhost ~]# hostnamectl set-hostname php
[root@localhost ~]# bash
[root@php ~]#

LAMP部署

创建lamp目录
[root@ansible ~]# cd /usr/src/
[root@ansible src]# mkdir lamp

复制ansible.cfg文件到当前目录 
[root@ansible lamp]# cp /etc/ansible/ansible.cfg .
[root@ansible lamp]# vim ansible.cfg
[defaults]

# some basic default values...

inventory      = inventory  #前面注释取消,再改为inventory


编写inventory清单文件
[root@ansible lamp]# vim inventory

[webservice]
apache.example.com

[dbservice]
database

[phpservice]
php.example.com

# 使用ping模块是否能ping通
[root@ansible lamp]# ansible all -m ping
php.example.com | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
apache.example.com | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
database | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

# 配置关闭防火墙跟SElinux的 playbook,需要关闭就引用
[root@ansible lamp]# cat off_firewalld.yml
- name: off firewalld
  servier:
    name: firewalld
    state: stopped
    enabled: no
[root@ansible lamp]# cat off_selinux.yml
- name: off selinux
  lineinfile:
    path: /etc/selinux/config
    regexp: '^SElinux'
    line: SELINUX=disabled



创建files目录存放软件或文件
[root@ansible lamp]# pwd
/usr/src/lamp
[root@ansible lamp]# mkdir files

# 进入files目录里下载Apr、Apr-util、httpd软件包
[root@ansible lamp]# cd files/
[root@ansible files]#  wget https://downloads.apache.org/apr/apr-1.7.0.tar.gz
[root@ansible files]#  wget https://downloads.apache.org/apr/apr-util-1.6.1.tar.gz
[root@ansible files]#  wget https://downloads.apache.org/httpd/httpd-2.4.54.tar.gz

# 下载MySQL软件包
[root@ansible files]# wget https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz

# 下载PHP软件包
[root@ansible files]# wget https://www.php.net/distributions/php-7.4.29.tar.xz

# 下载依赖包,因为基础源跟epel源没有这个包
[root@ansible files]# http://mirror.centos.org/centos/8-stream/PowerTools/x86_64/os/Packages/oniguruma-devel-6.8.2-2.el8.x86_64.rpm

[root@ansible files]# ls
apr-1.7.0.tar.gz       mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz
apr-util-1.6.1.tar.gz  oniguruma-devel-6.8.2-2.el8.x86_64.rpm
httpd-2.4.54.tar.gz    php-7.4.29.tar.xz


创建vars目录来设置变量
[root@ansible lamp]# mkdir vars

# 可以测试跑一下
[root@ansible lamp]# vim mail.yml
---
- hosts: all
  gather_facts: no
  tasks:
    - include_tasks: off_firewalld.yml
    - include_tasks: off_selinux.yml

[root@ansible lamp]# ls
ansible.cfg  inventory  off_firewalld.yml  vars
files        mail.yml   off_selinux.yml

考虑一个问题,受控的三台主机它们是否有yum源,是否是需要给他们配置yum源,如果需要你就引用进去

# 把基础源和epel源复制到当前目录
[root@ansible ~]# cd /usr/src/lamp/files
[root@ansible files]# cp /etc/yum.repos.d/* .

# 因为也复制ansible源过来了所以需要删除,如果你没有忽略它
[root@ansible files]# rm -f CentOS-SIG-ansible-29.repo

[root@ansible files]# ls 
epel-modular.repo  
apr-1.7.0.tar.gz  
epel.repo     
mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz  
apr-util-1.6.1.tar.gz  
epel-testing-modular.repo  
CentOS-Base.repo  epel-testing.repo   oniguruma-devel-6.8.2-2.el8.x86_64.rpm
httpd-2.4.54.tar.gz php-7.4.29.tar.xz  

# 配置yum源,如果你的系统已经yum源,可以忽略。
[root@ansible lamp]# vim yum.yml
- name: test /tmp/test_yum is exists
  command: test -f /tmp/test_yum
  register: yum_result
  ignore_errors: yes
- name: del yum  # 删除自带yum源
  shell: rm -rf /etc/yum.repos.d/* 2>&1 | tee /tmp/test_yum 
  when: yum_result['rc'] != 0
  ignore_errors: yes
- name: provide yum # 提供yum源
  copy:
    src: "{{ item }}" # 因yum源有多个,所以变量的方式
    dest: /etc/yum.repos.d/
  loop: "{{ yum }}"

如果需要就引用进去。

下载依赖包有很多所以需要用到变量vars目录

[root@ansible lamp]# vim vars/httpd.yml
# 依赖包
apache_depend_pkgs:  
  - openssl-devel
  - pcre-devel
  - expat-devel
  - libtool
  - gcc
  - gcc-c++
  - make
# 软件包
apache_soft_pkgs:
  - apr-1.7.0.tar.gz
  - apr-util-1.6.1.tar.gz
  - httpd-2.4.54.tar.gz
# yum源
yum:
  - CentOS-Base.repo  # 基础源是需要的
  - epel-modular.repo
  - epel.repo
  - epel-testing-modular.repo
  - epel-testing.repo
  
# 这些是后面添加虚拟主机时加的
WEB_PORT: 80
PHP_PORT: 9000
domain_name: test.example.com
php_web_dir: /test.example.com
install_dir: /usr/local/apache

配置apache

apache的playbook,引用到mail.yml
[root@ansible lamp]# vim apache.yml
- name: create user # 创建系统用户
  user:
    name: apache
    state: present
    system: yes
    create_home: no
    shell: /sbin/nologin
- name: test boost-deve is exists # 测试这个包是否存在
  shell: rpm -qa|grep boost-devel # 执行的结果传给boost_result
  register: boost_result # 上一条命令执行的结果传到这里
  ignore_errors: yes # 忽略错误
- name: install gcc error solve
  shell: yum -y install boost-devel --allowerasing # 安装 gcc 报错所以需要安装这个包
  when: boost_result['rc'] != 0 # 安装这个包的条件是不等于0
  ignore_errors: yes

- name: install depend pkgs # 安装依赖包
  yum:
    name: "{{ item }}" # 依赖包有多个的情况下建议用变量
    state: present
  loop: "{{ apache_depend_pkgs }}"
- name: provide software pkgs # 把软件包传给apache受控主机
  copy:
    src: "{{ item }}"
    dest: /usr/src/
  loop: "{{ apache_soft_pkgs }}"

- name: exec script  # 配置脚本
  script: files/apache.sh
# 脚本内容apache.sh
[root@ansible lamp]# cd files/
[root@ansible files]# cat apache.sh
#!/bin/bash

install_dir=/usr/local/apache # 在脚本里定义变量

cd /usr/src
if [ ! -d /usr/src/apr-1.7.0 ];then 
    tar xf apr-1.7.0.tar.gz
    sed -i '/$RM "$cfgfile"/d' apr-1.7.0/configure
fi

if [ ! -d /usr/src/apr-util-1.6.1 ];then
    tar xf apr-util-1.6.1.tar.gz
fi

if [ ! -d /usr/src/httpd-2.4.54 ];then
    tar xf httpd-2.4.54.tar.gz
fi


if [ ! -d /usr/local/apr ];then
    cd apr-1.7.0
    ./configure --prefix=/usr/local/apr && \
     make && make install
fi

if [ ! -d /usr/local/apr-util ];then
    cd ../apr-util-1.6.1
    ./configure --prefix=/usr/local/apr-util --with-apr=/usr/local/apr && \
    make && make install
fi

if [ ! -d $install_dir ];then
    cd ../httpd-2.4.54
    ./configure --prefix=$install_dir \
          --enable-so \
          --enable-ssl \
          --enable-cgi \
          --enable-rewrite \
          --with-zlib \
          --with-pcre \
          --with-apr=/usr/local/apr \
          --with-apr-util=/usr/local/apr-util/ \
          --enable-modules=most \
          --enable-mpms-shared=all \
          --with-mpm=prefork && \
    make && make install
fi

if [ ! -f /etc/profile.d/apache.sh ];then
    echo "export PATH=$install_dir/bin:\$PATH" > /etc/profile.d/apache.sh
fi

if [ ! -h $install_dir/include ];then
    ln -s $install_dir/include /usr/include/apache
    echo "MANDATORY_MANPATH     $install_dir/man" >> /etc/man_db.conf
fi

if [ ! -f /usr/lib/systemd/system/httpd.service ];then
cat > /usr/lib/systemd/system/httpd.service <<EOF
[Unit]
Description=httpd server daemon
After=network.target sshd-keygen.target

[Service]
Type=forking
ExecStart=$install_dir/bin/apachectl start
ExecStop=$install_dir/bin/apachectl stop
ExecReload=/bin/kill -HUP \$MAINPID

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
fi

ps -ef|grep httpd | grep -v grep
if [ $? -ne 0 ];then
systemctl enable --now httpd
fi
[root@ansible files]# chmod +x apache.sh # 给执行权限
[root@ansible files]# ll apache.sh  -d
-rwxr-xr-x. 1 root root 1854 Jul 30 15:58 apache.sh

可以测试跑一下

[root@ansible lamp]# vim mail.yml
- name: deploy apache
  hosts: apache.example.com
  vars_files:
    - vars/httpd.yml
  gather_facts: no
  tasks:
    - include_tasks: off_firewalld.yml # 需要关闭防火墙就引用
    - include_tasks: off_selinux.yml # 需要关闭SElinux就引用
    - include_tasks: yum.yml # 需要配置yum源就引用
    - include_tasks: apache.yml
# apache 的基本配置已经写完,测试跑一下

配置MySQL

[root@ansible lamp]# vim mysql.yml
- name: create user # 创建系统用户
  user:
    name: mysql
    state: present
    system: yes
    create_home: no
    shell: /sbin/nologin
- name: install depend pkgs # 安装依赖包
  yum:
    name: "{{ item }}"
    state: present
  loop: "{{ mysql_depend_pkgs }}"
- name: provide software pkgs
  copy:
    src: files/mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz
    dest: /usr/src/
- name: exec script
  script: files/mysql.sh
vars/mysql.yml的内容
[root@ansible lamp]# vim vars/mysql.yml

mysql_depend_pkgs:
  - ncurses-compat-libs
  - openssl-devel
  - openssl
  - cmake
  - mariadb-devel
yum:
  - CentOS-Base.repo
mysql.sh脚本内容
[root@ansible lamp]# vim  files/mysql.sh
#!/bin/bash

install_dir=/usr/local/mysql # 定义变量
data_dir=/opt/data # 定义变量

cd /usr/src/
if [ ! -d mysql-5.7.37-linux-glibc2.12-x86_64 ];then
    tar xf mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz
fi


if [ ! -d $install_dir ];then
    mv mysql-5.7.37-linux-glibc2.12-x86_64 $install_dir
    chown -R mysql.mysql $install_dir
fi

if [ ! -f /etc/profile.d/mysql.sh ];then
    echo "export PATH=$install_dir/bin:\$PATH" > /etc/profile.d/mysql.sh
fi

if [ ! -d /usr/include/mysql ];then
    ln -s $install_dir/include /usr/include/mysql
    echo "MANDATORY_MANPATH   $install_dir/man" >> /etc/man_db.conf
fi

if [ ! -f /etc/ld.so.conf.d/mysql.conf ];then
    $install_dir/lib
fi

# 创建存放数据目录
if [ ! -d $data_dir ];then
    mkdir $data_dir
    chown -R mysql.mysql $data_dir
fi

# 配置脚本启动服务
if [ ! -f $install_dir/support-files/mysqld ];then
    cd $install_dir/support-files
    cp mysql.server mysqld
    chown -R mysql.mysql mysqld
    sed -ri "s#^(basedir=).*#\1$install_dir#g" mysqld
    sed -ri "s#^(datadir=).*#\1$data_dir#g" mysqld
fi

# 初始化结果放到/tmp/pass,再用awk把密码取出来,登录进去修改密码
if [ ! -f /tmp/pass ];then
    $install_dir/bin/mysqld --initialize --user=mysql --datadir=$data_dir 2>&1 | tee /tmp/pass
fi

# 生成配置文件
cat > /etc/my.cnf <<EOF
[mysqld]
basedir = $install_dir
datadir = $data_dir
socket = /tmp/mysql.sock
port = 3306
pid-file = $data_dir/mysql.pid
user = mysql
skip-name-resolve
EOF

# 配置service文件
if [ ! -f /usr/lib/systemd/system/mysqld.service ];then
cat > /usr/lib/systemd/system/mysqld.service <<EOF
[Unit]
Description=mysql server daemon
After=network.target sshd-keygen.target

[Service]
Type=forking
ExecStart=$install_dir/support-files/mysqld start
ExecStop=$install_dir/support-files/mysqld stop
ExecReload=/bin/kill -HUP \$MAINPID

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload # 刷新程序
fi

ss -antl|grep "3306"
if [ $? -ne 0 ];then
    systemctl enable --now mysqld
    $install_dir/bin/mysql -uroot -p$(cat /tmp/pass | awk 'NR==9{print $NF}') --connect-expired-password -e "set password = password('123456')" #登录再修改密码123456
fi

配置PHP

# 创建php的页面
[root@ansible ~]# cd /usr/src/lamp/files/
[root@ansible files]# vim index.php
<?php
    phpinfo();
?>


[root@ansible lamp]# vim php.yml
- name: provide software pkgs
  copy:
    src: "{{ item }}"
    dest: /usr/src/
  loop: "{{ php_soft_pkgs }}"

- name: test boost-deve is exists
  shell: rpm -qa|grep boost-devel
  register: boost_result
  ignore_errors: yes
- name: install gcc error solve
  shell: yum -y install boost-devel --allowerasing
  when: boost_result['rc'] != 0
  ignore_errors: yes

- name: install depend pkgs
  yum:
    name: "{{ item }}"
    state: present
  loop: "{{ php_depend_pkgs }}"

- name: exec script
  script: files/php.sh

- name: provide index.php
  copy:
    src: files/index.php
    dest: "{{ php_web_dir }}"
  notify:
    - restart php   # 更改配置文件后触发重启服务

脚本内容php.sh

[root@ansible lamp]# cat files/php.sh
#!/bin/bash

php_web_dir=/test.example.com
install_dir=/usr/local/php7

cd /usr/src
if [ ! -d /usr/src/php-7.4.29 ];then
    tar xf php-7.4.29.tar.xz
    yum -y install oniguruma-devel-6.8.2-2.el8.x86_64.rpm
    cd php-7.4.29
    ./configure --prefix=$install_dir  \
        --with-config-file-path=/etc \
        --enable-fpm \
        --enable-inline-optimization \
        --disable-debug \
        --disable-rpath \
        --enable-shared \
        --enable-soap \
        --with-openssl \
        --enable-bcmath \
        --with-iconv \
        --with-bz2 \
        --enable-calendar \
        --with-curl \
        --enable-exif  \
        --enable-ftp \
        --enable-gd \
        --with-jpeg \
        --with-zlib-dir \
        --with-freetype \
        --with-gettext \
        --enable-json \
        --enable-mbstring \
        --enable-pdo \
        --with-mysqli=mysqlnd \
        --with-pdo-mysql=mysqlnd \
        --with-readline \
        --enable-shmop \
        --enable-simplexml \
        --enable-sockets \
        --with-zip \
        --enable-mysqlnd-compression-support \
        --with-pear \
        --enable-pcntl \
        --enable-posix && \
    make && make install
fi

if [ ! -f /etc/profile.d/php7.sh ];then
    echo "export PATH=$install_dir/bin:\$PATH" > /etc/profile.d/php7.sh
fi

if [ ! -h /usr/include/php7 ];then
    ln -s $install_dir/include /usr/include/php7
fi

if [ ! -f /etc/ld.so.conf.d/php7.conf ];then
    echo "$install_dir/lib" > /etc/ld.so.conf.d/php7.conf
fi

if [ ! -f /etc/init.d/php-fpm ];then
    cd /usr/src/php-7.4.29
    \cp php.ini-production /etc/php.ini
    cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
    chmod +x /etc/init.d/php-fpm
    cp $install_dir/etc/php-fpm.conf.default $install_dir/etc/php-fpm.conf

fi

if [ ! -f $install_dir/etc/php-fpm.d/www.conf ];then
    cd $install_dir/etc/php-fpm.d
    cp www.conf.default www.conf
    echo "listen = 192.168.229.151:9000" >> www.conf
    echo ";listen.allowed_clients = 192.168.229.148" >> www.conf
fi

if [ ! -f /usr/lib/systemd/system/php.service ];then
cat > /usr/lib/systemd/system/php.service <<EOF
[Unit]
Description=php-fpm server daemon
After=network.target sshd-keygen.target

[Service]
Type=forking
ExecStart=/etc/init.d/php-fpm start
ExecStop=/usr/bin/kill -9 \$MAINPID
ExecReload=/usr/bin/kill -HUP \$MAINPID

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
fi


if [ ! -d $php_web_dir ];then
    mkdir $php_web_dir
fi

ss -antl|grep "9000"
if [ $? -ne 0 ];then
    systemctl enable --now php
fi

php变量vars/php.yml

[root@ansible lamp]# vim vars/php.yml
  - libpng
  - libpng-devel
  - openldap-devel
  - pcre-devel
  - freetype
  - freetype-devel
  - gmp
  - gmp-devel
  - libmcrypt
  - libmcrypt-devel
  - readline
  - readline-devel
  - libxslt
  - libxslt-devel
  - sqlite-devel
  - libzip-devel
  - php-mysqlnd

yum:
  - CentOS-Base.repo
  - epel-testing-modular.repo
  - epel-modular.repo
  - epel-testing.repo
  - epel.repo

配置apache的主文件

# 复制apache的主配置文件到当前目录
[root@ansible ~]# cd /usr/src/lamp/files/
[root@ansible files]# scp root@apache.example.com:/usr/local/apache/conf/httpd.conf .
httpd.conf                              100%   18KB  12.5MB/s   00:00

# 进行修改
启用代理模块
[root@ansible files]# vim httpd.conf
LoadModule proxy_module modules/mod_proxy.so # 取消前面的注释
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so # 取消前面的注释

# 搜索AddType,添加以下内容
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
    AddType application/x-httpd-php .php     #添加此行
    AddType application/x-httpd-php-source .phps   #添加此行

# 搜索index.html,添加以下内容    
<IfModule dir_module>
    DirectoryIndex index.php  index.html  # 添加 index.php
</IfModule>


# 包含虚拟主机
# Virtual hosts
Include conf/extra/httpd-vhosts.conf # 把前面的注释取消

# 搜索80  
#Listen 12.34.56.78:80
Listen 192.168.229.148:80 # 在80的前面添加apache主机的ip

# 修改完后在使用模块传到apache受控机

配置虚拟主机

# 把apache的虚拟主机文件复制到当前目录
[root@ansible ~]# cd /usr/src/lamp/files/
[root@ansible files]# scp root@192.168.229.148:/usr/local/apache/conf/extra/httpd-vhosts.conf .
httpd-vhosts.conf                     100% 1465   715.4KB/s   00:00

[root@ansible lamp]# vim files/httpd-vhosts.conf
<VirtualHost *:{{ WEB_PORT }}>
    DocumentRoot "{{ install_dir }}/htdocs"
    ServerName {{ domain_name }}
    ErrorLog "logs/{{ domain_name }}-error_log"
    CustomLog "logs/{{ domain_name }}-access_log" common
    ProxyRequests Off
    ProxyPassMatch ^/(.*\.php)$ fcgi://192.168.229.151:{{ PHP_PORT }}{{ php_web_dir }}/$1
    <Directory "{{ php_web_dir }}">
        Options none
        AllowOverride none
        Require all granted
    </Directory>
</VirtualHost>

# 修改完后在使用模块传到apache受控机
apache 最终的内容
apache的playbook,引用到mail.yml
[root@ansible lamp]# vim apache.yml
- name: create user # 创建系统用户
  user:
    name: apache
    state: present
    system: yes
    create_home: no
    shell: /sbin/nologin
- name: test boost-deve is exists # 测试这个包是否存在
  shell: rpm -qa|grep boost-devel # 执行的结果传给boost_result
  register: boost_result # 上一条命令执行的结果传到这里
  ignore_errors: yes # 忽略错误
- name: install gcc error solve
  shell: yum -y install boost-devel --allowerasing # 安装 gcc 报错所以需要安装这个包
  when: boost_result['rc'] != 0 # 安装这个包的条件是不等于0
  ignore_errors: yes

- name: install depend pkgs # 安装依赖包
  yum:
    name: "{{ item }}" # 依赖包有多个的情况下建议用变量
    state: present
  loop: "{{ apache_depend_pkgs }}"
- name: provide software pkgs # 把软件包传给apache受控主机
  copy:
    src: "{{ item }}"
    dest: /usr/src/
  loop: "{{ apache_soft_pkgs }}"

- name: exec script  # 配置脚本
  script: files/apache.sh


- name: provide apache mail config file  # 添加
  copy:
    src: files/httpd.conf
    dest: "{{ install_dir }}/conf/httpd.conf"
  notify: 
    - restart httpd  # 更改配置文件后触发重启服务

- name: provide virtual host file # 添加
  template:
    src: files/httpd-vhosts.conf.j2
    dest: "{{ install_dir }}/conf/extra/httpd-vhosts.conf"
  notify:
    - restart httpd # 更改配置文件后触发重启服务

mail.yml内容

[root@ansible lamp]# vim mail.yml
---
- name: deploy apache
  hosts: apache.example.com
  vars_files:
    - vars/httpd.yml
  gather_facts: no
  tasks:
    - include_tasks: off_firewalld.yml
    - include_tasks: off_selinux.yml
    - include_tasks: yum.yml  # 引用yum源,如果你系统已有yum源,忽略它
    - include_tasks: apache.yml
  handlers:
    - name: restart httpd # 更改配置文件后触发重启服务
      service:
        name: httpd
        state: restarted

- name: deploy mysql
  gather_facts: no
  vars_files:
    - vars/mysql.yml
  hosts: database
  tasks:
    - include_tasks: off_firewalld.yml
    - include_tasks: off_selinux.yml
    - include_tasks: yum.yml # 引用yum源,如果你系统已有yum源,忽略它
    - include_tasks: mysql.yml

- name: deploy php
  gather_facts: no
  vars_files:
    - vars/php.yml
  hosts: php.example.com
  tasks:
    - include_tasks: off_firewalld.yml
    - include_tasks: off_selinux.yml
    - include_tasks: yum.yml # 引用yum源,如果你系统已有yum源,忽略它
    - include_tasks: php.yml
  handlers: 
    - name: restart php # 更改配置文件后触发重启服务
      service:
        name: php
        state: restarted

测试

ip 访问

在这里插入图片描述

在这里插入图片描述

域名访问

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Ansible分离部署LNMP可以让你更轻松地管理和部署LNMP服务器。以下是一些基本步骤: 1. 安装Ansible 2. 创建Ansible inventory文件,包含LNMP服务器的IP地址。 3. 创建Ansible playbook文件,指定要安装的软件包。 4. 在Ansible playbook文件中定义任务,例如安装Nginx、MySQLPHP。 5. 运行Ansible playbook文件,Ansible将自动在LNMP服务器上安装和配置软件。 下面是一个可能的示例Ansible playbook文件: ``` --- - hosts: lnmp_servers become: true vars: nginx_version: 1.18.0 mysql_version: 5.7 php_version: 7.4 tasks: - name: Install Nginx yum: name: nginx-{{ nginx_version }} state: present - name: Start Nginx service: name: nginx state: started - name: Install MySQL yum: name: mysql-server-{{ mysql_version }} state: present - name: Start MySQL service: name: mysqld state: started - name: Install PHP yum: name: php-{{ php_version }} php-fpm-{{ php_version }} state: present - name: Start PHP-FPM service: name: php-fpm state: started ``` 在这个示例中,我们假设我们有一个名为"lnmp_servers"的Ansible组,其中包含我们要部署LNMP的服务器的IP地址。此外,我们定义了要安装的软件包的版本号,并在任务中安装和启动Nginx、MySQLPHP。 运行Ansible playbook文件的命令是: ``` ansible-playbook -i inventory_file playbook_file.yml ``` 其中,inventory_file是你的Ansible inventory文件的路径,playbook_file.yml是你的Ansible playbook文件的路径。 这就是使用Ansible分离部署LNMP的基本步骤。你可以根据你的具体需求进行修改和定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值