前言

Ansible 是一个开源软件供应,配置管理和应用程序部署工具。它可以在许多类 Unix 系统上运行,并且可以配置类似 Unix 的系统以及 Microsoft Windows。它包含自己的声明性语言来描述系统配置。

环境准备

ANSIBLE 192.168.1.10
NGINX+PHP 192.168.1.20
MYSQL 192.168.1.30
NGINX负载均衡 192.168.1.40

ansible安装

基于linux系统安装

wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
yum install ansible -y
ansible --version

设置免密登录(master)

[root@master ~]# ssh-keygen  -t  rsa
[root@master ~]# ssh-copy-id  192.168.1.20
[root@master ~]# ssh-copy-id  192.168.1.30
[root@master ~]# ssh-copy-id  192.168.1.40

添加ip解析

[root@localhost]# vim /etc/ansible/hosts
# Here's another example of host ranges, this time there are no
# leading 0s:

## db-[99:101]-node.example.com
192.168.1.20
192.168.1.30
192.168.1.40
[clong]  #安装在哪一台
192.168.1.20   #nginx+php
[mysql]
192.168.1.30  #mysql

创建文件编写文件安装nginx

[root@localhost]# mkdir nginx
[root@localhost]# cd nginx
[root@localhost nginx]# vim nginx.yaml
---
- hosts: clong
  remote_user: root
  gather_facts: no
  tasks:
    # 安装epel源
    - name: install epel-release repo
      yum: name=epel-release state=present
    # 安装libselinux-python
    - name: install libselinux-python
      yum: name=libselinux-python state=present
    # 配置nginx最新稳定版源
    - name: copy nginx.repo
      copy: src=nginx.repo dest=/etc/yum.repos.d/nginx.repo
    # 更新yum缓存
    - name: update yum cache -1
      command: yum clean all
    - name: update yum cache -2
      command: yum makecache
    # 安装nginx
    - name: install nginx
      yum: name=nginx state=present
    # 开启nginx
    - name: start nginx
      service: name=nginx state=started enabled=yes
    # 复制nginx配置文件
    - name: copy nginx conf
      copy: src=nginx.conf dest=/etc/nginx/nginx.conf backup=yes force=yes
    # 验证配置文件
    - name: check nginx.conf
      shell: /usr/sbin/nginx -t -c /etc/nginx/nginx.conf
    # 删除默认的default.conf文件
    - name: delete default.conf
      file: path=/etc/nginx/conf.d/default.conf state=absent
    # 复制www站点文件
    - name: copy www conf
      copy: src=www.conf dest=/etc/nginx/conf.d/www.conf backup=yes force=yes
      notify: restart nginx
    # 重启nginx
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted
    # --syntax-check

[root@localhost nginx]# vim nginx.conf
user  nginx nginx;
worker_processes  auto;
worker_cpu_affinity auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    use epoll;
    multi_accept off;
    accept_mutex off;
    worker_connections  65535;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    server_names_hash_bucket_size 128;
    client_body_timeout 15;
    send_timeout 15;
    large_client_header_buffers 4 32k;
    client_header_timeout 15;

    charset UTF-8;
    server_tokens off;

    sendfile  on;
    sendfile_max_chunk 512k;

    tcp_nopush  on;
    tcp_nodelay on;

    keepalive_timeout  60;
    keepalive_requests 100000;
    reset_timedout_connection on;

    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;

    gzip  on;
    gzip_min_length  10240;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_proxied expired no-cache no-store private auth;
    gzip_disable "MSIE [1-6].";
    gzip_comp_level 2;
    gzip_types   text/plain text/css text/xml text/javascript  application/json application/x-javascript application/xml application/xml+rss;
    gzip_vary on;

    open_file_cache max=102400 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
    open_file_cache_errors on;

    include /etc/nginx/conf.d/*.conf;

}

[root@localhost nginx]# vim www.conf
server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/share/nginx/html;
        index  index.php index.html index.htm;
    }

    location ~ \.php {
        root           /usr/share/nginx/html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
    access_log  /var/log/nginx/host.access.log  main;
}

[root@localhost nginx]# vim nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1

[root@localhost nginx]# ansible-playbook nginx.yaml //运行yaml文件安装nginx

网页访问192.168.1.20

在这里插入图片描述

创建文件编写文件安装php

[root@localhost]# cd
[root@localhost]# mkdir php
[root@localhost]# cd php
[root@localhost php]# vim php.yaml
- hosts: clong
  remote_user: root
  gather_facts: no
  tasks:
    # 安装libselinux-python
    - name: isntall libselinux-python
      yum: name=libselinux-python state=present
    # 安装epel源
    - name: install epel-release repo
      yum: name=epel-release state=present
    # 安装rpm包
    - name: install remote php rpm
      yum: name=http://rpms.famillecollet.com/enterprise/remi-release-7.rpm state=present
    # 安装php5.6
    - name: install php
      yum: name={{ item }} state=present enablerepo=remi enablerepo=remi-php56
      with_items:
       - php
       - php-opcache
       - php-devel
       - php-mbstring
       - php-mcrypt
       - php-mysqlnd
       - php-phpunit-PHPUnit
       - php-pecl-xdebug
       - php-pecl-xhprof
       - php-mysql
       - php-pecl-apcu
       - php-pdo
       - php-pear
       - php-fpm
       - php-cli
       - php-xml
       - php-bcmath
       - php-process
       - php-gd
       - php-common
       - php-json
       - php-pdo_dblib
       - php-pgsql
       - php-recode
       - php-snmp
       - php-soap
       - php-pecl-zip
       - libjpeg*
       - php-imap
       - php-ldap
       - php-odbc
       - php-xmlrpc
       - php-mbstring
       - php-bcmath
       - php-mhash
       - libmcrypt
       - libmcrypt-devel
    # 开启php-fpm
    - name: start php-fpm
      service: name=php-fpm state=started enabled=yes
    # 复制index.php文件到网站根目录
    - name: copy index.php
      copy: src=index.php dest=/usr/share/nginx/html/index.php
      notify: restart nginx
    # 重启nginx
  handlers:
    - name: restart nginx
      service: name=nginx state=restarted

[root@localhost php]# vim index.php
<?php
    echo phpinfo();
?> 

[root@localhost php]# ansible-playbook php.yaml 

网页访问192.168.1.20/index.php

在这里插入图片描述

创建文件编写文件安装mysql

[root@localhost]# cd
[root@localhost]# mkdir mysql
[root@localhost]# cd mysql
[root@localhost mysql]# vim mysql.yaml
- hosts: mysql
  remote_user: root
  gather_facts: no
  tasks:
    # 安装rpm包
    - name: install remote mysql rpm
      yum: name=http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm state=present
    # 安装mysql
    - name: install mysql
      yum: name=mysql-server state=present
    # 开启mysql
    - name: start mysql
      service: name=mysqld state=started enabled=yes

[root@localhost mysql]# ansible-playbook mysql.yaml

设置mysql密码

```bash'
[root@localhost ~]# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!

In order to log into MySQL to secure it, we'll need the current
password for the root user. If you've just installed MySQL, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.

Set root password? [Y/n] y
New password:


## 登录mysql

```bash
[root@localhost ~]# mysql -u root -p123
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 16
Server version: 5.6.49 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

安装负载均衡

安装 zlib-devel、pcre-devel 等依赖包

[root@localhost ~]# yum -y install gcc gcc-c++ make libtool zlib zlib-devel pcre pcre-devel opensll openssl-devel

安装nginx 安装所需文件 提取码:u2ly

[root@nginx ~]# groupadd  nginx
//创建nginx的运行账户nginx,加入到nginx组中,不允许nginx直接登录系统
[root@nginx ~]# useradd -g nginx nginx -s /sbin/nologin
[root@nginx ~]# tar zxf nginx-1.14.0.tar.gz -C /usr/src/
[root@nginx ~]# unzip nginx-sticky-module.zip -d /usr/src/
[root@nginx ~]# cd /usr/src/nginx-1.14.0/
[root@localhost nginx-1.14.0 ~]# ./configure --prefix=/usr/local/nginx1.14  --user=nginx --group=nginx --with-http_stub_status_module  --with-http_realip_module --with-http_ssl_module --with-http_gzip_static_module  --http-client-body-temp-path=/var/tmp/nginx/client  --http-proxy-temp-path=/var/tmp/nginx/proxy  --http-fastcgi-temp-path=/var/tmp/nginx/fcgi --with-pcre --with-http_flv_module  --add-module=/usr/src/nginx-sticky-module  
[root@nginx nginx-1.14.0]# make && make install

优化nginx程序的执行路径

[root@nginx nginx-1.14.0]# ln -s /usr/local/nginx1.14/sbin/nginx /usr/local/sbin/
[root@nginx nginx-1.14.0]# nginx -t
nginx: the configuration file /usr/local/nginx1.14/conf/nginx.conf syntax is ok
nginx: [emerg] mkdir() "/var/tmp/nginx/client" failed (2: No such file or directory)
nginx: configuration file /usr/local/nginx1.14/conf/nginx.conf test failed

这里会报错,根据提示创建相应的目录即可

[root@nginx nginx-1.14.0]# mkdir -p /var/tmp/nginx/client
[root@nginx nginx-1.14.0]# chown -R nginx:nginx /var/tmp/nginx/
[root@nginx nginx-1.14.0]# nginx -t
nginx: the configuration file /usr/local/nginx1.14/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx1.14/conf/nginx.conf test is successful

编写nginx服务脚本

[root@nginx ~]# cat /etc/init.d/nginx 
#!/bin/bash 
# chkconfig: 2345 99 20 
# description: Nginx Service Control Script 
PROG="/usr/local/nginx1.14/sbin/nginx"
PIDF="/usr/local/nginx-1.14/logs/nginx.pid"
case "$1" in
  start)
   netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
   if [ $? -eq 0 ]
   then
     echo "Nginx service already running." 
   else
     $PROG -t &> /dev/null
     if [ $? -eq 0 ] ; then
       $PROG
       echo "Nginx service start success."
     else
     $PROG -t
     fi
   fi
   ;;
  stop)
   netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/nul
   if [ $? -eq 0 ]
   then
    kill -s QUIT $(cat $PIDF)
    echo "Nginx service stop success."
   else
    echo "Nginx service already stop"
   fi
   ;;
  restart)
    $0 stop
    $0 start
    ;;
  status)
   netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/null
   if [ $? -eq 0 ]
   then
     echo "Nginx service is running."
   else
     echo "Nginx is stop."
   fi
  ;;
  reload)
   netstat -anplt |grep ":80" &> /dev/null && pgrep "nginx" &> /dev/nul
   if [ $? -eq 0 ]
   then
    $PROG -t &> /dev/null
    if [ $? -eq 0 ] ; then
      kill -s HUP $(cat $PIDF)
      echo "reload Nginx config success."
    else
      $PROG -t
    fi
   else
    echo "Nginx service is not run."
   fi
    ;;
  *)
   echo "Usage: $0 {start|stop|restart|reload}"
   exit 1
esac

测试脚本是否能用

[root@nginx ~]# chmod +x /etc/init.d/nginx 
[root@nginx ~]# nginx  -t
[root@nginx ~]# chkconfig --add nginx
[root@nginx ~]# chkconfig nginx on
[root@nginx ~]# /etc/init.d/nginx start
Nginx service start success.
[root@nginx ~]# netstat -anput | grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      6162/nginx: master

修改nginx配置文件

[root@localhost ~]# vim /usr/local/nginx1.14/conf/nginx.conf
# http模块下添加
upstream backend {
        server 192.168.1.30:80 max_fails=2 fail_timeout=10s;
        server 192.168.1.40:80 max_fails=2 fail_timeout=10s;
        sticky;
}
# location模块添加
        location / {
            root   html;
            index  index.html index.htm;
            proxy_pass http://backend;
        }
[root@nginx ~]# nginx -s reload   //重启nginx

访问192.168.1.40是否会出现php页面

在这里插入图片描述

访问成功