ansible-playbook-[第4部分]-roles 角色

Ansible-playbook 角色目錄結構:

files:存放需要同步到異地服務器的源碼文件及配置文件,至少應該包含一個main.yml文件。其他文件需要在此文件中通過include包含調用; 
handlers:當資源發生變化時需要進行的操作,若沒有此目錄可以不建或爲空,至少應該包含一個main.yml文件。其他文件需要在此文件中通過include包含調用; 
tasks:nginx安裝過程成需要進行的執行的任務; 至少應該包含一個main.yml文件。其他文件需要在此文件中通過include包含調用
templates:用於執行nginx安裝的模板文件,一般爲腳本; 
vars:本次安裝定義的變量,至少應該包含一個main.yml文件。其他文件需要在此文件中通過include包含調用

實例:ansible-playbook 安裝nginx

#目錄結構如下:
├── nginx_install.yml            #總入口
└── roles                        #角色目錄
    └── nginx_install                        
        ├── files                
        │   ├── html404.tgz
        │   └── nginx-1.18.0.tar.gz
        ├── handlers
        │   └── main.yml
        ├── tasks
        │   ├── copy.yml
        │   ├── install.yml
        │   ├── main.yml
        │   └── prepare.yml
        ├── templates
        │   ├── fastcgi_params
        │   ├── nginx.conf.j2
        │   ├── nginx.service
        │   └── server.conf
        └── vars
            └── main.yml


[ 1 ]  創建角色相關目錄:
mkdir -p roles/nginx_install/{files,handlers,tasks,templates,vars}


[2]  創建總入口文件:
[root@git-server app_server]# cat nginx_install.yml 
#用於批量安裝Nginx
- hosts: aly
  remote_user: root
  gather_facts: True

  roles:
    - nginx_install #角色目錄名

[3]  查看files目錄下文件:

[root@git-server app_server]# ll roles/nginx_install/files/
-rw-r--r-- 1 root root   75560 Jan  8 19:25 html404.tgz
-rw-r--r-- 1 root root 1039530 Apr 21  2020 nginx-1.18.0.tar.gz


[4]  查看templates目錄下文件:

[root@git-server app_server]# ll roles/nginx_install/templates/
-rw-r--r-- 1 root root  849 Jan  8 16:31 fastcgi_params
-rw-r--r-- 1 root root 1490 Jan  8 19:32 nginx.conf.j2
-rw-r--r-- 1 root root  429 Jan  8 16:30 nginx.service
-rw-r--r-- 1 root root 1914 Jan  8 19:53 server.conf

cat roles/nginx_install/templates/fastcgi_params

[root@git-server templates]# cat fastcgi_params 
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

cat nginx.conf.j2 

user nobody nobody;    
worker_processes  {{ansible_processor_vcpus+1}};
error_log {{ DATA_DIR }}/log/error.log crit;
pid /run/nginx.pid;
worker_rlimit_nofile 51200;

events {
    use epoll;
    worker_connections  1024;
}

http {
    include       mime.types;
    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  {{ DATA_DIR }}/log/access.log  main;
    
    sendfile            on;
    send_timeout        3m;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    client_header_timeout 3m;
    client_body_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 30m;
    client_body_buffer_size 256k;
    client_body_temp_path {{ NGINX_DIR }}/client_body_temp;
    proxy_temp_path {{ NGINX_DIR }}/proxy_temp;
    fastcgi_temp_path {{ NGINX_DIR }}/fastcgi_temp;
    fastcgi_intercept_errors on;    

    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm 
    application/xml;

    default_type  application/octet-stream;
    include  {{ NGINX_DIR }}/conf/vhost/*.conf;
}

[root@git-server templates]# cat server.conf 

 server {
     listen       80;
     server_name  localhost;
     location / {
           root   {{ NGINX_DIR }}/html;
           index  index.php index.html index.htm;
      } 
      error_page  500 502 503 504  /50x.html;
    location = /50x.html {  
       root {{ NGINX_DIR }}/html;
    }      
    error_page   404 403 404  /404x.html;
    location = /404x.html {
       root {{ NGINX_DIR }}/html;
    }    
    location /status {
      stub_status on;
      access_log   off;
    }
 }

 #反向代理-負載均衡 
 #upstream test{
 #    server localhost:5080 down;
 #    server localhost:5080 backup;
 #    server localhost:5080  max_fails=1 fail_timeout=10s;
 #    server localhost:5080  max_fails=1 fail_timeout=10s;
 #}
 #server {
 #      listen       80;
 #      server_name  localhost;
 #      location / {
 #          charset utf-8;
 #          index  index.jsp index.html index.htm;
 #          proxy_pass        http://test;
 #          proxy_redirect off;
 #          proxy_set_header Host $host;
 #          proxy_set_header X-Real-IP $remote_addr;
 #          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 #          client_max_body_size 500m;
 #          client_body_buffer_size 1024k;
 #          proxy_connect_timeout 30000;
 #          proxy_read_timeout 30000;
 #          proxy_send_timeout 30000;
 #          proxy_buffer_size 512k;
 #          proxy_buffers   32 256k;
 #          proxy_busy_buffers_size 512k;
 #          proxy_temp_file_write_size 512k;
 #          fastcgi_buffers 32 512k;
 #      }
 #      location /status{ 
 #           stub_status on;
 #           access_log   off;
 #      }
 #         error_page   500 502 503 504  /50x.html;
 #         location = /50x.html {
 #          root {{ NGINX_DIR }}/html;
 #      }
 #      error_page   404 403 404  /404x.html;
 #      location = /404x.html {
 #      root {{ NGINX_DIR }}/html;
 #      }
 #}
 #----------------------------------------------------

[root@git-server templates]# cat nginx.service 

[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre={{ NGINX_DIR }}/sbin/nginx -t
ExecStart={{ NGINX_DIR }}/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target



[5]  創建基礎系統環境配置yml文件:

cat roles/nginx_install/tasks/prepare.yml 
- name: 關閉firewalld
  service: name=firewalld state=stopped enabled=no

- name: 臨時關閉 selinux
  shell: "setenforce 0"
  failed_when: false

- name: 永久關閉 selinux
  lineinfile:
    dest: /etc/selinux/config
    regexp: "^SELINUX="
    line: "SELINUX=disabled"

- name: 添加EPEL倉庫
  yum: name=epel-release state=latest

- name: 安裝常用軟件包
  yum:
    name:
      - vim
      - lrzsz
      - net-tools
      - wget
      - curl
      - bash-completion
      - rsync
      - gcc
      - gcc-c++
      - unzip
      - git
      - autoconf
      - cmake
      - openssl
      - openssl-devel
      - pcre 
      - pcre-devel 
      - zlib
      - zlib-devel
      - gd-devel
      - libxml2-devel
    state: latest
#
#- name: 更新系統
#  shell: "yum update -y"
#  args:
#    warn: False


[5]  創建軟件安裝基礎環境yml配置文件:

cat roles/nginx_install/tasks/copy.yml 
- name: 創建nginx用戶組
  group: name={{ NGINX_USER }}  state=present

- name: 創建nginx用戶
  user: name={{ NGINX_USER }}  group={{ NGINX_USER }}  state=present create_home=False shell=/sbin/nologin

- name: 創建software目錄
  file: name={{ SOURCE_DIR }} state=directory mode=0755 recurse=yes
  
- name: 創建日誌目錄
  file: name={{ item }} state=directory owner={{ NGINX_USER }} group={{ NGINX_USER }} mode=0755 recurse=yes
  with_items:
  - "{{ DATA_DIR }}"
  - "{{ DATA_DIR }}/log"
  
- name: 創建日誌文件
  file: name={{ item }} state=touch owner={{ NGINX_USER }} group={{ NGINX_USER }} mode=0644
  with_items:
  - "{{ DATA_DIR }}/log/access.log"
  - "{{ DATA_DIR }}/log/error.log"

#當前主機下沒有nginx包
#- name: 下載nginx包
#  unarchive: src={{ DOWNLOAD_URL }} dest={{ SOURCE_DIR }} owner={{ NGINX_USER }} group={{ NGINX_USER }} copy=no

#當前主機file目錄下已有nginx包
- name: 拷貝並解壓nginx包
  unarchive: src=nginx-{{ NGINX_VER }}.tar.gz dest={{ SOURCE_DIR }} owner={{ NGINX_USER }} group={{ NGINX_USER }} copy=yes

#複製nginx服務文件
- name: 拷貝nginx服務文件
  template: src=nginx.service dest=/usr/lib/systemd/system/nginx.service owner=root group=root

[6]  創建軟件安裝yml文件:

cat roles/nginx_install/tasks/
copy.yml     install.yml  main.yml     prepare.yml  
[root@git-server app_server]# cat roles/nginx_install/tasks/
copy.yml     install.yml  main.yml     prepare.yml  
[root@git-server app_server]# cat roles/nginx_install/tasks/install.yml 
#編譯nginx
- name: 編譯nginx
  shell: "cd {{ SOURCE_DIR }}/nginx-{{ NGINX_VER }} && ./configure --prefix={{ NGINX_DIR }} --user={{ NGINX_USER }} --group={{ NGINX_USER }} --http-log-path={{ DATA_DIR }}/log/access.log --error-log-path={{ DATA_DIR }}/log/error.log --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module --with-http_stub_status_module"
  
#安裝nginx
- name: 安裝nginx
  shell: "cd {{ SOURCE_DIR }}/nginx-{{ NGINX_VER }} && make && make install"
  
#複製nginx主配置文件
- name: 拷貝nginx主配置文件
  template: src=nginx.conf.j2 dest={{ NGINX_DIR }}/conf/nginx.conf owner={{ NGINX_USER }} group={{ NGINX_USER }}
  notify: 重啓nginx

- name: 創建vhost配置文件目錄
  file: name={{ NGINX_DIR }}/conf/vhost state=directory owner={{ NGINX_USER }} group={{ NGINX_USER }} mode=0755 recurse=yes

#複製nginx vhost配置文件
- name: 拷貝nginx vhost配置文件
  template: src=server.conf dest={{ NGINX_DIR }}/conf/vhost/server.conf owner={{ NGINX_USER }} group={{ NGINX_USER }} mode=0644
  notify: 重啓nginx

#複製nginx額外配置文件
- name: 拷貝nginx額外配置文件
  template: src=fastcgi_params dest={{ NGINX_DIR }}/conf/fastcgi_params owner={{ NGINX_USER }} group={{ NGINX_USER }} mode=0644
  notify: 重啓nginx

#拷貝錯誤頁面文件
- name: 拷貝404錯誤頁面文件
  unarchive: src=html404.tgz dest={{ NGINX_DIR }}/html/ copy=yes

#創建測試首頁文件
- name: 創建測試首頁文件
  shell: echo wo shi minte server > {{ NGINX_DIR }}/html/index.html

#拷貝複製
- name: 配置環境變量
  shell: " if [ `grep {{ NGINX_DIR }}/sbin /etc/profile |wc -l` -eq 0 ]; then echo export PATH=$PATH:{{ NGINX_DIR }}/sbin >> /etc/profile && source /etc/profile; else source /etc/profile; fi"

- name: 啓動nginx並開機啓動
  shell: "systemctl daemon-reload && systemctl enable nginx && systemctl start nginx"

- name: 服務可用性測試
  uri: url=http://{{ ansible_default_ipv4['address'] }}

#  register: return_value
#  - fail: 
#    msg: 'check nginx  false'
#    when: "'200' not in return_value.stdout"

[7]  創建task 入口文件:

cat roles/nginx_install/tasks/main.yml 
- include: prepare.yml
- include: copy.yml
- include: install.yml

[8]  創建handlers 入口文件:

cat roles/nginx_install/handlers/main.yml 
- name: 重啓nginx
  service: name=nginx state=restarted

[9]  創建task 入口文件:

cat roles/nginx_install/vars/main.yml 
NGINX_VER: 1.18.0
DOWNLOAD_URL: http://nginx.org/download/nginx-{{ NGINX_VER }}.tar.gz
NGINX_USER: nginx
NGINX_PORT: 80
SOURCE_DIR: /usr/local/src/
NGINX_DIR: /usr/local/nginx
DATA_DIR: /data/nginx


[10]  執行安裝:

ansible-playbook -C nginx_install.yml
ansible-playbook  nginx_install.yml




總結:====================================================================
1. 可以安裝多個角色如:安裝部署三個角色
---
-    hosts: websrvs
    remote_user: root
    roles:
        - mysql
        - memcached
        - nginx
方法2:
-    hosts: websrvs
    remote_user: root
    roles:
        - mysql
        - memcached
    -         -    { role: nginx,username: nginx} 

2.main.yml 規定了所有文件的執行順序,當然也可以將所以文件內容全部寫入到mian.yml中,但不建議

vim tasks/main.yml 
- include: install.yml
- include: config.yml
- include: index.yml
- include: service.yml

3.可以給角色打標籤,執行的時候可以根據標籤進行選擇執行,同時也可以加入when條件

#調用角色執行時,加入when條件,當系統爲centos7的時候,執行安裝nginx
roles中 定義tags標籤,可以給角色定義多個標籤,執行的時候,可以選擇標籤來執行
如:
```
---
cat web.yml
-    hosts: websrvs
    remote_user: root
    roles:
        - { role: mysql,tags: ['mysql','db'] }
        - { role: maiadb,tags: ['maiadb','db'] }
        -    { role: nginx,tags:['nginx','web'],username: nginx, when: ansible_distribution_major_version == '7'}

#執行
ansible-playbook --tags="nginx,httpd,mysql" web.yml

4.模板文件必須 用到變量且參數計算的,則需要以js結尾,循環計算語法規則:j2語言;可進行for,while循環 if判斷等操作,如果不需要進行計算,只是調用變量,則無需以j2結尾。
如:
cat templates/nginx.conf.j2
user nginx nginx;
worker_processes {{ansible_processor_vcpus+3}}; #變量參與了計算
#通常是CPU核的數量存儲數據的硬盤數量及負載模式;可將其改成cpu內核數
worker_rlimit_nofile 65535;
......

cat templates/server.conf #文件名無需以j2結尾.只是調用變量,沒有進行計算,當然此文件可以放到files目錄中
server {
     listen       80;
     server_name  localhost;
     location / {
           root   {{ NGINX_DIR }}/html;
           index  index.php index.html index.htm;
      } 
 }

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章