天天看点

【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详解

乐维论坛