1. 程式人生 > >使用Ansible搭建LNMP

使用Ansible搭建LNMP

安裝Ansible

yum -y install ansible

如果copy報錯一下的語句 "msg": "Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!",需要安裝支援包

yum -y install libselinux-python

然後建立roles的標準化模組相應的目錄

[[email protected] myroles]# tree /myroles/
/myroles/
├── nginx.yaml  #nginx模組入口配置檔案
└── roles
    └── nginx   #nginx原型模組目錄
        ├── files
        ├── handlers
        ├── tasks
        │   └── main.yaml   #nginx模組的tasks任務配置檔案
        ├── templates
        └── vars
7 directories, 2 files

Nginx的劇本書寫,在myroles裡,跟roles同級

---
- hosts: all   
  gather_facts: True    
  roles:         
  - nginx 

然後在Nginx目錄下files目錄裡放置安裝包和,安裝指令碼檔案

nginx的搭建指令碼

#!/bin/bash
mkdir -p /media/cdrom
umount /dev/sr0 &>/dev/null
mount /dev/sr0 /media/cdrom &>/dev/null
dir=/etc/yum.repos.d
[ 
-d $dir ] || mkdir -p $dir cd $dir mv * /tmp/ cat >/etc/yum.repos.d/local.repo << KOF [local] name=localrepo baseurl=file:///media/cdrom/ KOF yum -y clean all &>/dev/null [ $? -eq 0 ] || echo "clean erro" yum makecache &>/dev/null || echo "erro cache" which "wget" [ $? -eq 0 ] || /usr/bin/yum -y install wget &>/dev/null
/usr/bin/wget http://mirrors.aliyun.com/repo/epel-6.repo [ $? -eq 0 ] || (/bin/echo "yun源出錯" && exit) /usr/bin/yum -y clean all &>/dev/null /usr/bin/yum makecache &>/dev/null [ $? -eq 0 ] || (/bin/echo "yun快取錯誤" && exit) /usr/bin/yum -y install pcre-deved openssl-devel &>/dev/null [ $? -eq 0 ] || /bin/echo "pcre error" useradd -M -s /sbin/nologin nginx &>dev/null cd ~ tar xf nginx-1.10.2.tar.gz -C /usr/src/ cd /usr/src/nginx-1.10.2/ ./configure --user=nginx --group=nginx --prefix=/usr/local/nginx-1.10.2/ --with-http_stub_status_module --with-http_ssl_module && make && make install &>/dev/null

在tasks裡建立個main.yaml主要任務劇本

- name: t1
  copy: src=nginx-1.10.2.tar.gz dest=/root/
  register: ttt
- debug: var=ttt
- name: t2
  script: nginx.sh
  register: rrr
- debug: var=rrr

回到mysoles裡執行nginx.yaml劇本

[[email protected] myroles]# ansible-playbook nginx.yaml 

PLAY [all] *************************************************************************************************

TASK [Gathering Facts] *************************************************************************************
ok: [web1]
ok: [web2]

TASK [nginx : t1] ******************************************************************************************
ok: [web2]
ok: [web1]

TASK [nginx : debug] ***************************************************************************************
ok: [web1] => {
    "ttt": {
        "changed": false, 
        "checksum": "1bafb1557b8d5f992714c0dcbde77036bde98547", 
        "dest": "/root/nginx-1.10.2.tar.gz", 
        "diff": {
            "after": {
                "path": "/root/nginx-1.10.2.tar.gz"
            }, 
            "before": {
                "path": "/root/nginx-1.10.2.tar.gz"
            }
        }, 
        "failed": false, 
        "gid": 0, 
        "group": "root", 
        "mode": "0644", 
        "owner": "root", 
        "path": "/root/nginx-1.10.2.tar.gz", 
        "secontext": "unconfined_u:object_r:admin_home_t:s0", 
        "size": 910812, 
        "state": "file", 
        "uid": 0
    }
}
ok: [web2] => {
    "ttt": {
        "changed": false, 
        "checksum": "1bafb1557b8d5f992714c0dcbde77036bde98547", 
        "dest": "/root/nginx-1.10.2.tar.gz", 
        "diff": {
            "after": {
                "path": "/root/nginx-1.10.2.tar.gz"
            }, 
            "before": {
                "path": "/root/nginx-1.10.2.tar.gz"
            }
        }, 
        "failed": false, 
        "gid": 0, 
        "group": "root", 
        "mode": "0644", 
        "owner": "root", 
        "path": "/root/nginx-1.10.2.tar.gz", 
        "secontext": "unconfined_u:object_r:admin_home_t:s0", 
        "size": 910812, 
        "state": "file", 
        "uid": 0
    }
}

TASK [nginx : t2] ******************************************************************************************
changed: [web2]
changed: [web1]

TASK [nginx : debug] ***************************************************************************************
ok: [web1] => {
    "rrr": {
        "changed": true, 
        "failed": false, 
        "rc": 0, 
        "stderr": "Shared connection to 192.168.200.131 closed.\r\n", 
        "stderr_lines": [
            "Shared connection to 192.168.200.131 closed."
        ], 
        "stdout": "/usr/bin/wget\r\n--2018-11-12 19:02:03--  http://mirrors.aliyun.com/repo/epel-6.repo\r\nResolving mirrors.aliyun.com... failed: Name or service not known.\r\nwget: unable to resolve host address “mirrors.aliyun.com”\r\nyun源出錯\r\n", 
        "stdout_lines": [
            "/usr/bin/wget", 
            "--2018-11-12 19:02:03--  http://mirrors.aliyun.com/repo/epel-6.repo", 
            "Resolving mirrors.aliyun.com... failed: Name or service not known.", 
            "wget: unable to resolve host address “mirrors.aliyun.com”", 
            "yun源出錯"
        ]
    }
}
ok: [web2] => {
    "rrr": {
        "changed": true, 
        "failed": false, 
        "rc": 0, 
        "stderr": "Shared connection to 192.168.200.133 closed.\r\n", 
        "stderr_lines": [
            "Shared connection to 192.168.200.133 closed."
        ], 
        "stdout": "/usr/bin/wget\r\n--2018-11-12 16:03:20--  http://mirrors.aliyun.com/repo/epel-6.repo\r\nResolving mirrors.aliyun.com... 122.72.3.220, 122.72.3.219, 122.72.3.221, ...\r\nConnecting to mirrors.aliyun.com|122.72.3.220|:80... connected.\r\nHTTP request sent, awaiting response... 200 OK\r\nLength: 664 [application/octet-stream]\r\nSaving to: “epel-6.repo”\r\n\r\n\r 0% [                                       ] 0           --.-K/s              \r100%[======================================>] 664         --.-K/s   in 0s      \r\n\r\n2018-11-12 16:03:21 (62.4 MB/s) - “epel-6.repo” saved [664/664]\r\n\r\n", 
        "stdout_lines": [
            "/usr/bin/wget", 
            "--2018-11-12 16:03:20--  http://mirrors.aliyun.com/repo/epel-6.repo", 
            "Resolving mirrors.aliyun.com... 122.72.3.220, 122.72.3.219, 122.72.3.221, ...", 
            "Connecting to mirrors.aliyun.com|122.72.3.220|:80... connected.", 
            "HTTP request sent, awaiting response... 200 OK", 
            "Length: 664 [application/octet-stream]", 
            "Saving to: “epel-6.repo”", 
            "", 
            "", 
            " 0% [                                       ] 0           --.-K/s              ", 
            "100%[======================================>] 664         --.-K/s   in 0s      ", 
            "", 
            "2018-11-12 16:03:21 (62.4 MB/s) - “epel-6.repo” saved [664/664]", 
            ""
        ]
    }
}

PLAY RECAP *************************************************************************************************
web1                       : ok=5    changed=1    unreachable=0    failed=0   
web2                       : ok=5    changed=1    unreachable=0    failed=0

這樣Nginx服務就先簡單的搭建成功,需要主要目前沒有任何的配置檔案和啟動服務

搭建mysql,roles的模板

[[email protected] ~]# tree /myroles/
/myroles/
├── mysql.retry
├── mysql.yaml
├── nginx.retry
├── nginx.yaml
└── roles
    ├── mysql
    │?? ├── files
    │?? │?? ├── mysql-5.5.32-linux2.6-x86_64.tar.gz
    │?? │?? ├── mysql.sh
    │?? │?? └── yum.sh
    │?? ├── handlers
    │?? ├── tasks
    │?? │?? └── main.yaml
    │?? ├── templates
    │?? └── vars
    ├── nginx
    │?? ├── files
    │?? │?? ├── nginx-1.10.2.tar.gz
    │?? │?? └── nginx.sh
    │?? ├── handlers
    │?? ├── tasks
    │?? │?? └── main.yaml
    │?? ├── templates
    │?? └── vars
    └── php
        ├── files
        ├── handlers
        ├── tasks
        ├── templates
        └── vars

mysql.yaml的內容

---
- hosts: all
  gather_facts: True
  roles:
  - mysql

tasks裡邊的任務

[[email protected] tasks]# vim main.yaml 
- name: t1
  copy: src=mysql-5.5.32-linux2.6-x86_64.tar.gz dest=/root/
  register: ttt
- debug: var=ttt
- name: t2
  script: mysql.sh
  register: rrr
- debug: var=rrr

files裡邊的指令碼

yum的指令碼

#!/bin/bash
mkdir -p /media/cdrom
umount /dev/sr0 &>/dev/null
mount /dev/sr0 /media/cdrom &>/dev/null
dir=/etc/yum.repos.d
[ -d $dir ] || mkdir -p $dir
cd $dir
mv * /tmp/
cat >/etc/yum.repos.d/local.repo << KOF
[local]
name=localrepo
baseurl=file:///media/cdrom/
KOF
yum -y clean all &>/dev/null
[ $? -eq 0 ] || echo "clean erro"
yum makecache &>/dev/null || echo "erro cache"
which "wget"
[ $? -eq 0 ] || /usr/bin/yum -y install wget &>/dev/null
/usr/bin/wget http://mirrors.aliyun.com/repo/epel-6.repo
[ $? -eq 0 ] || (/bin/echo "yun源出錯" && exit)
/usr/bin/yum -y clean all &>/dev/null
/usr/bin/yum makecache &>/dev/null
[ $? -eq 0 ] || (/bin/echo "yun快取錯誤" && exit)
/usr/bin/yum -y install pcre-deved openssl-devel &>/dev/null
[ $? -eq 0 ] || /bin/echo "pcre error"

mysl的安裝指令碼(需要注意的是這裡使用的是二進位制壓縮包,簡單的指令碼,不嚴謹,可以執行成功)

#!/bin/bash
groupadd mysql
useradd -s /sbin/nologin -g mysql -M mysql
cd ~
tar xf mysql-5.5.32-linux2.6-x86_64.tar.gz -C /usr/local/
cd /usr/local/
mv mysql-5.5.32-linux2.6-x86_64 mysql-5.5.32
ln -s mysql-5.5.32 mysql
[ -d /usr/local/mysql/data ] || mkdir -p /usr/local/mysql/data
chown -R mysql.mysql /usr/local/mysql
yum -y install libaio
/usr/local/mysql/scripts/mysql_install_db --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql
cd /usr/local/mysql
cp support-files/mysql.server /etc/init.d/mysqld
chmod +x /etc/init.d/mysqld
/etc/init.d/mysqld start

執行mysql劇本

[[email protected] myroles]# ansible-playbook mysql.yaml 
PLAY [all] *****************************************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [web1]

TASK [mysql : t1] **********************************************************************************************************************************************************
ok: [web1]

TASK [mysql : debug] *******************************************************************************************************************************************************
ok: [web1] => {
    "ttt": {
        "changed": false, 
        "checksum": "1861329e637aca5e143c436fd795d28ed8f10729", 
        "dest": "/root/mysql-5.5.32-linux2.6-x86_64.tar.gz", 
        "diff": {
            "after": {
                "path": "/root/mysql-5.5.32-linux2.6-x86_64.tar.gz"
            }, 
            "before": {
                "path": "/root/mysql-5.5.32-linux2.6-x86_64.tar.gz"
            }
        }, 
        "failed": false, 
        "gid": 0, 
        "group": "root", 
        "mode": "0644", 
        "owner": "root", 
        "path": "/root/mysql-5.5.32-linux2.6-x86_64.tar.gz", 
        "secontext": "system_u:object_r:admin_home_t:s0", 
        "size": 186722932, 
        "state": "file", 
        "uid": 0
    }
}

TASK [mysql : t2] **********************************************************************************************************************************************************
changed: [web1]

TASK [mysql : debug] *******************************************************************************************************************************************************
ok: [web1] => {
    "rrr": {
        "changed": true, 
        "failed": false, 
        "rc": 0, 
        "stderr": "Shared connection to 192.168.200.131 closed.\r\n", 
        "stderr_lines": [
            "Shared connection to 192.168.200.131 closed."
        ], 
        "stdout": "groupadd: group 'mysql' already exists\r\nuseradd: user 'mysql' already exists\r\nmv: cannot move `mysql-5.5.32-linux2.6-x86_64' to `mysql-5.5.32/mysql-5.5.32-linux2.6-x86_64': Directory not empty\r\nln: creating symbolic link `mysql/mysql-5.5.32': File exists\r\nLoaded plugins: fastestmirror\r\nLoading mirror speeds from cached hostfile\r\nSetting up Install Process\r\nPackage libaio-0.3.107-10.el6.x86_64 already installed and latest version\r\nNothing to do\r\nInstalling MySQL system tables...\r\nOK\r\nFilling help tables...\r\nOK\r\n\r\nTo start mysqld at boot time you have to copy\r\nsupport-files/mysql.server to the right place for your system\r\n\r\nPLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !\r\nTo do so, start the server, then issue the following commands:\r\n\r\n/usr/local/mysql/bin/mysqladmin -u root password 'new-password'\r\n/usr/local/mysql/bin/mysqladmin -u root -h www.sunan.com password 'new-password'\r\n\r\nAlternatively you can run:\r\n/usr/local/mysql/bin/mysql_secure_installation\r\n\r\nwhich will also give you the option of removing the test\r\ndatabases and anonymous user created by default.  This is\r\nstrongly recommended for production servers.\r\n\r\nSee the manual for more instructions.\r\n\r\nYou can start the MySQL daemon with:\r\ncd /usr/local/mysql ; /usr/local/mysql/bin/mysqld_safe &\r\n\r\nYou can test the MySQL daemon with mysql-test-run.pl\r\ncd /usr/local/mysql/mysql-test ; perl mysql-test-run.pl\r\n\r\nPlease report any problems with the /usr/local/mysql/scripts/mysqlbug script!\r\n\r\nStarting MySQL SUCCESS! \r\n", 
        "stdout_lines": [
            "groupadd: group 'mysql' already exists", 
            "useradd: user 'mysql' already exists", 
            "mv: cannot move `mysql-5.5.32-linux2.6-x86_64' to `mysql-5.5.32/mysql-5.5.32-linux2.6-x86_64': Directory not empty", 
            "ln: creating symbolic link `mysql/mysql-5.5.32': File exists", 
            "Loaded plugins: fastestmirror", 
            "Loading mirror speeds from cached hostfile", 
            "Setting up Install Process", 
            "Package libaio-0.3.107-10.el6.x86_64 already installed and latest version", 
            "Nothing to do", 
            "Installing MySQL system tables...", 
            "OK", 
            "Filling help tables...", 
            "OK", 
            "", 
            "To start mysqld at boot time you have to copy", 
            "support-files/mysql.server to the right place for your system", 
            "", 
            "PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !", 
            "To do so, start the server, then issue the following commands:", 
            "", 
            "/usr/local/mysql/bin/mysqladmin -u root password 'new-password'", 
            "/usr/local/mysql/bin/mysqladmin -u root -h www.sunan.com password 'new-password'", 
            "", 
            "Alternatively you can run:", 
            "/usr/local/mysql/bin/mysql_secure_installation", 
            "", 
            "which will also give you the option of removing the test", 
            "databases and anonymous user created by default.  This is", 
            "strongly recommended for production servers.", 
            "", 
            "See the manual for more instructions.", 
            "", 
            "You can start the MySQL daemon with:", 
            "cd /usr/local/mysql ; /usr/local/mysql/bin/mysqld_safe &", 
            "", 
            "You can test the MySQL daemon with mysql-test-run.pl", 
            "cd /usr/local/mysql/mysql-test ; perl mysql-test-run.pl", 
            "", 
            "Please report any problems with the /usr/local/mysql/scripts/mysqlbug script!", 
            "", 
            "Starting MySQL SUCCESS! "
        ]
    }
}

PLAY RECAP *****************************************************************************************************************************************************************
web1                       : ok=5    changed=1    unreachable=0    failed=0

如果報錯ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

是說明找不到sockt啟動檔案,第一個辦法是修改配置檔案的路徑

[[email protected] ~]# vim /etc/my.cnf 
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

第二個辦法是直接做個軟連線就可以

ln -s /var/lib/mysql/* /tmp/

安裝php

roles的樹形結構

[[email protected] php]# tree /myroles/
/myroles/
├── mysql.retry
├── mysql.yaml
├── nginx.retry
├── nginx.yaml
├── php.retry
├── php.yaml
└── roles
    ├── mysql
    │   ├── files
    │   │   ├── mysql-5.5.32-linux2.6-x86_64.tar.gz
    │   │   ├── mysql.sh
    │   │   └── yum.sh
    │   ├── handlers
    │   ├── tasks
    │   │   └── main.yaml
    │   ├── templates
    │   └── vars
    ├── nginx
    │   ├── files
    │   │   ├── nginx-1.10.2.tar.gz
    │   │   └── nginx.sh
    │   ├── handlers
    │   ├── tasks
    │   │   └── main.yaml
    │   ├── templates
    │   └── vars
    └── php
        ├── files
        │   ├── libiconv-1.14.tar.gz
        │   ├── php-5.3.28.tar.gz
        │   └── php.sh
        ├── handlers
        ├── tasks
        │   └── main.yaml
        ├── templates
        └── vars

php的劇本與roles平級的

[[email protected] myroles]# vim php.yaml
---
- hosts: all
  gather_facts: True
  roles:
  - php

php的tasks的劇本

[[email protected] tasks]# vim main.yaml
- name: t1
  copy: src=php-5.3.28.tar.gz dest=/root/
  register: ttt
- debug: var=ttt
- name: t3
  copy: src=libiconv-1.14.tar.gz dest=/root/
  register: ttt
- debug: var=ttt
- name: t2
  script: php.sh
  register: rrr
- debug: var=rrr

安裝php的指令碼

[[email protected] files]# pwd
/myroles/roles/php/files

[[email protected] files]# vim php.sh
#!/bin/bash
yum -y zlib-devel libxml2-devel libjpeg-devel libjpeg-turbo-devel libiconv-devel install freetype-devel libpng-devel gd libcurl-devel libxslt-devel
cd ~
tar xf libiconv-1.14.tar.gz -C /usr/src
cd /usr/src/libiconv-1.14
./configure --prefix=/usr/local/libiconv && make && make install
yum -y install libmcrypt-devel mhash mcrypt
useradd -s /sbin/nologin -M www
cd ~
tar xf php-5.3.28.tar.gz -C /usr/src/
cd /usr/src/php-5.3.28 && ./configure --prefix=/usr/local/php5.3.28 --with-mysql=mysqlnd --with-iconv-dir=/usr/local/libiconv --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --enable-short-tags --enable-zend-multibyte --enable-static --with-xsl --with-fpm-user=www --with-fpm-group=www --enable-ftp
make && make install
ln -s /usr/local/php5.3.28/ /usr/local/php
cd /usr/src/php-5.3.28
cp php.ini-production /usr/local/php/lib/php.ini
cd /usr/local/php/etc/
cp php-fpm.conf.default php-fpm.conf
/usr/local/php/sbin/php-fpm