天天看點

【Ansible】Ansible 自動編譯部署 nginx詳解

一、ansible簡介及測試環境

名稱 hostname IP
ansible node4 192.168.40.131
client node5 192.168.40.132

本次測試隻是用一台client做測試。但!!!!

ansible是新出現的自動化運維工具,基于Python開發,集合了衆多運維工具(puppet、cfengine、chef、func、fabric)的優點,實作了批量系統配置、批量程式部署、批量運作指令等功能。

ansible是基于子產品工作的,本身沒有批量部署的能力。真正具有批量部署的是ansible所運作的子產品,ansible隻是提供一種架構。主要包括:

(1)、連接配接插件connection plugins:負責和被監控端實作通信;

(2)、host inventory:指定操作的主機,是一個配置檔案裡面定義監控的主機;

(3)、各種子產品核心子產品、command子產品、自定義子產品;

(4)、借助于插件完成記錄日志郵件等功能;

(5)、playbook:劇本執行多個任務時,非必需可以讓節點一次性運作多個任務。

是以在批量部署時,隻需要在hosts檔案加入client主機IP即可。

二、安裝ansible

因為我的Linux的是CentOS Linux release 7.3.1611 (Core),使用的ali倉庫源。

我在yum安裝的ansible是

三、編寫nginx的roles模闆

先看看所需要的檔案

[root@node4 ansible]# pwd

/etc/ansible

[root@node4 ansible]# tree

.

├── ansible.cfg #核心配置檔案

├── hosts       #主機清單

├── nginx_install.yaml #playbook編譯安裝nginx檔案

└── roles

    └── nginx_install

        ├── default

        ├── files

        │   └── nginx-1.12.0.tar.gz #編譯安裝nginx的安裝包,提前下載下傳至此

        ├── handlers

        │   └── main.yml #觸發配置檔案

        ├── meta #中繼資料

        ├── tasks

        │   └── main.yml #定義要調用的nginx的主邏輯檔案

        ├── templates

        │   ├── nginx.conf #定義nginx的配置檔案

        │   └── nginx.service #定義nginx的啟動腳本(systemctl)

        └── vars

            └── main.yml #定義變量配置檔案

9 directories, 9 files

先建立所需要的目錄(必須一樣),而且上面配置檔案必須以main.yml命名。

必須設定ansible到各主機之間的ssh免秘鑰互信。

指令如下

ssh-keygen 

ssh-copy-id node5 #主機名或IP

mkdir -p roles/nginx_instll/{handlers,files,meta,tasks,templates,vars,default}

1、配置主要邏輯檔案:

[root@node4 ansible]# cat roles/nginx_install/tasks/main.yml 

- name: copy nginx package to remote host

  copy: src=nginx-1.12.0.tar.gz dest=/usr/local/src/nginx-1.12.0.tar.gz#調用files子產品(複制nginx-1.12.0.tar.gz至遠端)

  tags: cppkg

- name: tar nginx

  shell: cd /usr/local/src;tar -xf nginx-1.12.0.tar.gz

- name: install pakger

  yum: name={{item}} state=latest#使用變量解決依賴包的問題

  with_items: 

  - openssl-devel

  - pcre-devel

  - gcc

  tags: dpdpkg

- name: useradd nginx

  shell: useradd nginx

  tags: add_nginx

- name: install nginx

  shell: cd /usr/local/src/nginx-1.12.0;./configure --user=nginx --group=nginx --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre;make && make install

  tags: inngx

- name: copy start config

  template: src=nginx.service dest=//usr/lib/systemd/system/nginx.service#調用templates子產品

  notify: start nginx

- name: mkdir vhosts

  shell: mkdir /usr/local/nginx/vhosts

- name: copy config file nginx.conf

  template: src=nginx.conf dest=/usr/local/nginx/conf/nginx.conf

  notify: reload nginx service

2、将nginx-1.12.0.tar.gz複制到/etc/ansible/roles/nginx_install/files目錄下

3、配置templates下的檔案。

[root@node4 nginx_install]# ls templates/

nginx.conf  nginx.service

該目錄下的nginx.conf将推送到client主機。

[root@node4 templates]# cat nginx.conf 

#user  nobody;

worker_processes  {{ ansible_processor_vcpus }};#使用ansible的setup指令自動傳入

#error_log  logs/error.log;

#error_log  logs/error.log  notice;

#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {

    worker_connections  1024;

}

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  logs/access.log  main;

    sendfile        on;

    #tcp_nopush     on;

    #keepalive_timeout  0;

    keepalive_timeout  65;

    #gzip  on;

    server {

        listen      {{ ngxport }} ;#使用vars下自定義的變量

        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {

            root   {{ root_dir }};#使用vars下自定義的變量

            index  index.html index.htm;

        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html

        #

        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80

        #location ~ \.php$ {

        #    proxy_pass   

http://127.0.0.1

;

        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

        #    root           html;

        #    fastcgi_pass   127.0.0.1:9000;

        #    fastcgi_index  index.php;

        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

        #    include        fastcgi_params;

        # deny access to .htaccess files, if Apache's document root

        # concurs with nginx's one

        #location ~ /\.ht {

        #    deny  all;

    }

    # another virtual host using mix of IP-, name-, and port-based configuration

    #

    #server {

    #    listen       8000;

    #    listen       somename:8080;

    #    server_name  somename  alias  another.alias;

    #    location / {

    #        root   html;

    #        index  index.html index.htm;

    #    }

    #}

    # HTTPS server

    #    listen       443 ssl;

    #    server_name  localhost;

    #    ssl_certificate      cert.pem;

    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;

    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;

    #    ssl_prefer_server_ciphers  on;

    include vhosts/*.conf;#建立虛拟主機的包含檔案,友善下次批量管理

該目錄下的nginx.service将推送到client主機。該啟動腳本采用systemctl啟動。

[root@node4 nginx_install]# cat templates/nginx.service 

[Unit]

Description=nginx

After=network.target

[Service]

Type=forking

ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf

ExecStart=/usr/local/nginx/sbin/nginx

ExecReload=/usr/local/nginx/sbin/nginx  -s reload

ExecStop=/usr/local/nginx/sbin/nginx -s stop

PrivateTmp=true

[Install]

WantedBy=multi-user.target

4、配置vars下的檔案

在nginx.conf的配置檔案的變量部分可以選擇利用ansible調用系統,例如cup核心數:

[root@node4 nginx_install]# ansible 192.168.40.132 -m setup -a "filter=ansible_processor_vcpus"

192.168.40.132 | success >> {

    "ansible_facts": {

        "ansible_processor_vcpus": 1

    }, 

    "changed": false

是以nginx.conf中定義的

{{ ansible_processor_vcpus }}

是可以自動化轉入參數。

nginx.conf中其他剩下的變量屬于自定義,調用vars的配置檔案:

[root@node4 nginx_install]# cat vars/main.yml 

ngxport: "80"#監聽端口

server_name: "node5.aizhen.com"#通路域名

root_dir: "/web"#web主目錄

5、配置handlers下的檔案

在主邏輯檔案中:

  template: src=nginx.service dest=//usr/lib/systemd/system/nginx.service

  notify: start nginx #觸發到handlers的檔案

handlers的配置檔案

  1. [root@node4 nginx_install]# cat handlers/main.yml 
  2. - name: start nginx #這裡的名字必須與主邏輯檔案比對,否則觸發不了
  3.   service: name=nginx state=started
  4. - name: reload nginx service
  5.   service: name=nginx state=restarted

四、測試

1、檢測文法,看看是否正确。

[root@node4 ansible]# ansible-playbook --syntax-chec /etc/ansible/nginx_install.yaml 

playbook: /etc/ansible/nginx_install.yaml

确定沒有報錯。

2、使用tags,copy nginx的安裝包到client主機,防止出錯。

[root@node4 ansible]# ansible-playbook -t cppkg /etc/ansible/nginx_install.yaml 

PLAY [192.168.40.132] ********************************************************* 

GATHERING FACTS *************************************************************** 

ok: [192.168.40.132]

TASK: [nginx_install | copy nginx package to remote host] ********************* 

changed: [192.168.40.132]

PLAY RECAP ******************************************************************** 

192.168.40.132             : ok=2    changed=1    unreachable=0    failed=0   

檢視client

[root@node5 ~]# cd /usr/local/src/

[root@node5 src]# ls

nginx-1.12.0.tar.gz

測試安裝nginx

[root@node4 templates]# ansible-playbook /etc/ansible/nginx_install.yaml 

TASK: [nginx_install | tar nginx] ********************************************* 

TASK: [nginx_install | install pakger] **************************************** 

ok: [192.168.40.132] => (item=openssl-devel,pcre-devel,gcc)

TASK: [nginx_install | useradd nginx] ***************************************** 

TASK: [nginx_install | install nginx] ***************************************** 

TASK: [nginx_install | copy start config] ************************************* 

TASK: [nginx_install | mkdir vhosts] ****************************************** 

TASK: [nginx_install | copy config file nginx.conf] *************************** 

NOTIFIED: [nginx_install | start nginx] *************************************** 

NOTIFIED: [nginx_install | reload nginx service] ****************************** 

192.168.40.132             : ok=11   changed=8    unreachable=0    failed=0   

檢視client的80端口是否啟動

root@node5 ~]# netstat -ntlp

Active Internet connections (only servers)

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    

tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      1/systemd           

tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      11503/nginx: master 

tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      917/sshd            

tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1009/master         

tcp6       0      0 :::111                  :::*                    LISTEN      1/systemd           

tcp6       0      0 :::22                   :::*                    LISTEN      917/sshd            

tcp6       0      0 ::1:25                  :::*                    LISTEN      1009/master   

這就就完成部署啦。

五、測試出現報錯

[root@node4 templates]# ansible-playbook -C /etc/ansible/nginx_install.yaml 

skipping: [192.168.40.132]####這裡代表跳過shell的測試,因為第一次使用,無法檢測。

如果使用-C測試的話,會出現報錯

日志報錯如下:

Oct 25 2017 08:35:05 - SKIPPED - ...

Oct 25 2017 08:35:05 - OK - {"module_name": "shell", "module_args": "cd /usr/local/src;tar -xf nginx-1.12.0.tar.gz"}

=> {"msg": "check mode not supported for shell", "skipped": true}

這個問題也不說是報錯,隻是ansible識别不了而已。

因為主邏輯檔案中使用了shell。隻要直接推送即可。

轉自

ansible 自動編譯部署 nginx詳解

樂維論壇