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;
      } 
 }

 

 

 

 

 

 

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