Roles角色

就是把一个庞大的playbook拆分成多个子目录,每个子目录存放不同的文件

角色目录结构:

playbook1.yml 
playbook2.yml 
roles/ 
  project1/ 
    tasks/ 
    files/
    vars/ 
    templates/
    handlers/
    defaults/
    meta/ 
  project2/ 
    tasks/
    files/
    vars/
    templates/ 
    handlers/ 
    defaults/
    meta/

Roles各目录作用

roles/project/ :项目名称,有以下子目录 
1、files/ :存放由copy或script模块等调用的文件 
2、templates/:template模块查找所需要模板文件的目录 
3、tasks/:定义task,role的基本元素,至少应该包含一个名为main.yml的文件;其它的文件需要在此 文件中通过include进行包含 
4、handlers/:至少应该包含一个名为main.yml的文件;此目录下的其它的文件需要在此文件中通过 include进行包含 
5、vars/:定义变量,至少应该包含一个名为main.yml的文件;此目录下的其它的变量文件需要在此文件中通过include进行包含,也可以通过项目目录中的group_vars/all定义变量,从而实现角色通用代码和项目数据的分离
6、meta/:定义当前角色的特殊设定及其依赖关系,至少应该包含一个名为main.yml的文件,其它文 件需在此文件中通过include进行包含 
7、defaults/:设定默认变量时使用此目录中的main.yml文件,比vars的优先级低

创建脚色目录有两种办法:

第一种自己手动创建
第二种利用ansible命令创建角色目录的结构(但是创建的不一定需要,所以可以手动创建)
如:mkdir roles
cd roles
ansible-galaxy role init nginx  #使用工具创建nginx的文件夹
把以下nginx的二进制安装playbook.yaml文件写成角色
---
- hosts: 10.0.0.101
  vars:
          - nginx_url: http://nginx.org/download/nginx-1.22.0.tar.gz
          - install_dir: /apps
          - tar_dir: /usr/local
- download_dir: /root

  tasks:
          - name: vars_nginx_tar
            shell: echo {{nginx_url}} | basename {{nginx_url}}
            register: nginx_tar
          - name: vars_nginx_dir
            shell: echo {{ nginx_tar.stdout }} |sed -rn 's/(nginx.*)\..*\..*$/\1/p'
            register: nginx_dir
          - name: nginx -v
            shell: "{{ install_dir }}/nginx/sbin/nginx -v"
            register: nginx_v
            ignore_errors: yes

          - name: redhat 7
            yum: name=gcc,make,pcre-devel,openssl-devel,zlib-devel,perl-ExtUtils-Embed state=installed
            when: ansible_distribution_file_variety == "RedHat" and ansible_distribution_major_version |int == 7
            ignore_errors: yes
          - name: redhat 8
            yum: name=gcc,make,gcc-c++,libtool,pcre,pcre-devel,zlib,zlib-devel,openssl,openssl-devel,perl-ExtUtils-Embed state=installed
            when: ansible_distribution_file_variety == "RedHat" and ansible_distribution_major_version |int == 8
            ignore_errors: yes
          - name: ubuntu 20.04
            apt: update_cache=yes name=gcc,make,libpcre3,libpcre3-dev,openssl,libssl-dev,zlib1g-dev state=present
            when: ansible_distribution_file_variety == "Debian"
            ignore_errors: yes

          - name: create user nginx
            user: name=nginx system=yes shell=/usr/bin/false
          - name: dowmload tar.gz
            get_url: url={{ nginx_url }} dest={{ download_dir }}
          - name: unarchive
            unarchive: src={{ download_dir }}/{{ nginx_tar.stdout }} dest={{ tar_dir }} copy=no
          - name: create fir
            file: path={{ install_dir }} state=directory
          - name: shell
            shell: chdir={{ tar_dir }}/{{ nginx_dir.stdout }} ./configure --prefix={{ install_dir }}/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module && make -j {{ ansible_processor_vcpus }} && make install
            when: nginx_v.rc != 0
          - name: file owner group
            file: path={{ install_dir }}/nginx owner=nginx group=nginx recurse=yes
          - name: link nginx
            file: src={{ install_dir }}/nginx/sbin/nginx dest=/usr/sbin/nginx state=link
          - name: server file
            template: src=nginx.server.j2 dest=/usr/lib/systemd/system/nginx.service
            notify: nginx reload
          - name: create run dir
            file: path={{ install_dir }}/nginx/run state=directory
          - name: conf file
            template: src=nginx.conf.j2 dest={{ install_dir }}/nginx/conf/nginx.conf
            notify: nginx reload
          - name: daemon-reload
            shell: systemctl daemon-reload
          - name: enable nginx
            service: name=nginx state=started enabled=yes

  handlers:
          - name: nginx reload
            shell: nginx -s reload
根据以上内容需要创建以下目录

一:主机清单配置

vim /etc/ansible/hosts
[webservers]
10.0.0.103
10.0.0.102

二:打通GUK验证

[root@ubunt ansible]# ssh-copy-id 10.0.0.103
[root@ubunt ansible]# ssh-copy-id 10.0.0.102

三:变量

对谁进行安装ngixn  (可以把变量放在这里)
[root@ubunt ansible]# vim role_nginx.yaml
- hosts: 10.0.0.102
  vars:
    nginx_var: "1.22.0"
    nginx_user: "nginx"
    nginx_uid: 88
    nginx_group: "nginx"
    nginx_gid: 88
    tar_dir: "/usr/local/src"
    install_dir: "/apps/nginx"
    nginx_config_files: "conf.d/*.conf"
    
  roles:
  - nginx

四:创建子目录

[root@ubunt ansible]# mkdir roles/nginx/{tasks,templates,vars,files,handlers} -p
[root@ubunt ansible]# tree roles
roles
└── nginx
    ├── files
    ├── handlers
    ├── tasks
    ├── templates
    └── vars

6 directories, 0 files

五:进入tasks目录,创建main.yaml文件,作为执行入口

touch main.yaml (把所有任务都写入main.yaml或者每个任务写不同的文件,在main.yaml中使用include调用)

任务1:

tasks任务(安装依赖包)
[root@ubunt tasks]# vim packages.yaml
- name: redhat 7
  yum: name=gcc,make,pcre-devel,openssl-devel,zlib-devel,perl-ExtUtils-Embed state=installed
  when: ansible_distribution_file_variety == "RedHat" and ansible_distribution_major_version |int == 7
  ignore_errors: yes
- name: redhat 8
  yum: name=gcc,make,gcc-c++,libtool,pcre,pcre-devel,zlib,zlib-devel,openssl,openssl-devel,perl-ExtUtils-Embed state=installed
  when: ansible_distribution_file_variety == "RedHat" and ansible_distribution_major_version |int == 8
  ignore_errors: yes
- name: ubuntu 20.04
  apt: update_cache=yes name=gcc,make,libpcre3,libpcre3-dev,openssl,libssl-dev,zlib1g-dev state=present
  when: ansible_distribution_file_variety == "Debian"
  ignore_errors: yes

任务2:

tasks任务(创建用户和组)
[root@ubunt tasks]# vim user.yaml
- name: create group nginx {{ nginx_group }}
  group: name={{ nginx_group }} gid={{ nginx_gid }} system=yes
- name: create user nginx {{ nginx_user }}
  user: name={{ nginx_user }} group={{ nginx_group}} uid={{ nginx_uid }} system=yes shell=/usr/bin/false

任务3:

tasks任务(编译安装)
[root@ubunt tasks]# vim install.yaml
- name: unarchive
  unarchive: src=nginx-{{ nginx_var }}.tar.gz  dest={{ tar_dir }}
- name: shell
  shell: chdir={{ tar_dir }}/nginx-{{ nginx_var }} ./configure --prefix={{ install_dir }} --user={{ nginx_user }} --group={{ nginx_group }} --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module && make -j {{ ansible_processor_vcpus }} && make install
- name: data dir
  file: path={{ install_dir }}/run state=directory
- name: config dir
  file: path={{ install_dir }}/conf/conf.d state=directory
- name: file owner group
  file: path={{ install_dir }} owner={{ nginx_user }} group={{ nginx_group }} recurse=yes

任务4:

tasks任务(conf文件)
[root@ubunt tasks]# vim config.yaml
- name: conf file
  template: src=nginx.conf.j2 dest={{ install_dir }}/conf/nginx.conf
  notify: nginx reload

任务5:

tasks任务(service文件)
[root@ubunt tasks]# vim service.yaml
- name: service file
  template: src=nginx.server.j2 dest=/usr/lib/systemd/system/nginx.service
- name: daemon-reload
  shell: systemctl daemon-reload
- name: start service
  service: name=nginx state=started enabled=yes

六:handlers文件

handlers文件
[root@ubunt handlers]# vim main.yaml
- name: nginx reload
  shell: "{{ install_dir }}/sbin/nginx -s reload" #(对应conf文件的notify: nginx reload)

七:tasks下写一个总的main.yaml文件,用于调用5个任务

tasks下写一个总的main.yaml文件,用于调用config.yaml  install.yaml  packages.yaml  service.yaml  user.yaml这五个文件
[root@ubunt tasks]# vim main.yaml
- include: packages.yaml
- include: user.yaml
- include: install.yaml
- include: config.yaml
- include: service.yaml
按照顺序进行排列,依次执行。先安装依赖包,然后创建帐号,编译安装,准备配置文件,启服务。

八、下载放装包放files里面

files里面放安装包
下载nginx安装包,这样就不用每台机器下载了。
[root@ubunt files]# wget http://nginx.org/download/nginx-1.22.0.tar.gz
[root@ubunt files]# ls
nginx-1.22.0.tar.gz

九、准备模板文件(service文件和conf文件)

[root@ubunt templates]# cat nginx.conf.j2 
user  nginx;
worker_processes  auto;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;
pid        {{ install_dir }}/run/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       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            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
        #
        #location ~ \.php$ {
        #    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
    #
    #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;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
include {{ nginx_config_files }};
}


[root@ubunt templates]# cat nginx.service.j2
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile={{ install_dir }}/run/nginx.pid 
ExecStart={{ install_dir }}/sbin/nginx -c {{ install_dir }}/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
LimitNOFILE=100000
[Install]
WantedBy=multi-user.target

十:准备变量文件(变量不建议放在项目里面,可以放在与项目同级目录下),与第三步重复,可选一个

[root@ubunt vars]# vim main.yaml
nginx_var: "1.22.0"
nginx_user: "nginx"
nginx_uid: 88
nginx_group: "nginx"
nginx_gid: 88

tar_dir: "/usr/local/src"
install_dir: "/apps/nginx"
nginx_config_files: "conf.d/*.conf"

十一:准备nginx页面文件

在files文件中准备一个index.html文件
[root@ubunt nginx]# ls
files  handlers  tasks  templates  vars
[root@ubunt nginx]# echo Ansible WedSite > files/index.html

然后写一个data.yaml
[root@ubunt tasks]# vim data.yaml
- name: data files
  copy: src=index.html dest={{ install_dir }}/html/
  
把他写入总的main.yaml文件
[root@ubunt tasks]# vim main.yaml
- include: packages.yaml
- include: user.yaml
- include: install.yaml
- include: data.yaml
- include: config.yaml
- include: service.yaml
文件目录
[root@ubunt roles]# tree
.
└── nginx
    ├── files
    │   ├── index.html
    │   └── nginx-1.22.0.tar.gz
    ├── handlers
    │   └── main.yaml
    ├── tasks
    │   ├── config.yaml
    │   ├── data.yaml
    │   ├── install.yaml
    │   ├── main.yaml
    │   ├── packages.yaml
    │   ├── service.yaml
    │   └── user.yaml
    ├── templates
    │   ├── nginx.conf.j2
    │   └── nginx.server.j2
    └── vars
        └── main.yaml

6 directories, 13 files

十二:执行playbook

在和角色roles同级的目录下,写一个role_nginx.yaml来调用刚写的nginx角色
vim role_nginx.yaml
- hosts: 10.0.0.102
  
  roles:
  - nginx
然后执行这个文件
[root@ubunt ansible]# ansible-playbook role_nginx.yaml

十三:写一个网站

vim /apps/nginx/conf/conf.d/test.conf
server {
  listen 80;
  server_name www.test.com
  root /data/test/;
}

写入测试数据
mkdir /data/test -p
vim /data/test/index.html
www.test.com
语法检查
nginx -t
重载配置文件
nginx -s reload

访问
curl -H"hosts: www.test.com" 127.0.0.1
www.test.com
使用ansible Roles包安装php
第一步:创建目录
[root@ubunt roles]# mkdir php-fpm/{tasks,templates,handlers} -p
第二步:写总的tasks下的main.yaml文件
[root@ubunt roles]# cat php-fpm/tasks/main.yaml 
- include: packages.yaml
- include: config.yaml
- include: app.yaml
- include: service.yaml
第三步:写安装包文件
[root@ubunt roles]# vim php-fpm/tasks/packages.yaml
- name: install pachages
  apt: name={{ item }}    #loop循环
  loop:
   - php7.4-fpm    - php7.4-mysql    - php7.4-json 
   - php7.4-xml 
   - php7.4-mbstring 
   - php7.4-zip 
   - php7.4-gd 
   - php7.4-curl 
   - php-redis 
第四步:写配置文件(对应handlers)
[root@ubunt php-fpm]# vim tasks/config.yaml
- name: php config file
  template:
    src: www.conf.j2
    dest: /etc/php/7.4/fpm/pool.d/www.conf
  notify: restart php-fpm

- name: nginx config file
  template:  
    src: php.conf.j2
    dest: "{{ install_dir }}/conf/conf.d/php.conf"
  notify: restart nginx 
第五步:写一个测试页面,把测试页面当作app.yaml
[root@ubunt php-fpm]# mkdir files
[root@ubunt php-fpm]# vim files/index.php
<?php
phpinfo ();
?>
[root@ubunt tasks]# vim app.yaml
- name: create {{ php_path }}
  file:
    path: "{{ php_path }}/"
    state: directory
   
- name: app files
  copy:
    src: index.php
    dest: "{{ php_path }}/"
第六步:写启动文件
[root@ubunt tasks]# cat service.yaml 
- name: start php-fpm
  service: name=php7.4-fpm.service state=started enabled=yes   

第七步:准备php配置文件模板
[root@ubunt templates]# cp /etc/php/7.4/fpm/pool.d/www.conf /data/ansible/roles/php-fpm/templates/www.conf
[root@ubunt templates]# ls
www.conf.j2
[root@ubunt templates]#cat www.conf (可安装php后把配置文件cp到files目录下并修改以下内容)
[www]
user = "{{nginx_user}}"
group = "{{nginx_group}}"
listen = 127.0.0.1:9000

pm = dynamic
pm.max_childen =5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

pm.status_path = /status
ping.path = /ping


第八步:准备nginx页面配置模板
[root@ubunt templates]# vim php.conf.j2
server {
   listen 80;
   server_name {{ website_fqdn }};
   root {{ php_path }};                     
   index index.php;
   location ~ \.php$|ping|php-status {
            root           {{ php_path }};
            fastcgi_pass   127.0.0.1:9000; 
            fastcgi_index  index.php;        
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
   }
}
第九步:handlers(对应上面notify)
[root@ubunt handlers]# vim main.yaml
- name: restart php-fpm
  service: name=php7.4-fpm state=restarted
- name: restart nginx
  service: name=nginx state=restarted

这次变量放在项目里面

[root@ubunt ansible]# vim role_nginx_php.yaml
- hosts: 10.0.0.103
  vars:
    nginx_var: "1.22.0"
    nginx_user: "nginx"
    nginx_uid: 88
    nginx_group: "nginx"
    nginx_gid: 88
    tar_dir: "/usr/local/src"
    install_dir: "/apps/nginx"
    nginx_config_files: "conf.d/*.conf"
    website_fqdn: "www.test.com"
    php_path: "/data/php"

  roles:
  - role: nginx
  - role: php-fpm
    when:      
    - ansible_distribution_major_version == '20'     
    - ansible_distribution_file_variety == "Debian"

测试执行

[root@ubunt ansible]# ansible-playbook -C role_nginx_php.yaml  测试
[root@ubunt ansible]# ansible-playbook role_nginx_php.yaml     执行

在windows上做解析

10.0.0.103 www.test.com
然后在网页访问