roles基本概述

roles不管是Ansible还是saltstack,我在写一键部署的时候,都不可能把所有的步骤全部写入到一个'剧本'文件当中,我们肯定需要把不同的工作模块,拆分开来,解耦,那么说到解耦,我们就需要用到roles官方推荐,因为roles的目录结构层次更加清晰。
例如:我们之前推荐大家写一个base.yml里面写所有基础优化的项目,其实把所有东西摞进去也是很鸡肋的,不如我们把这些功能全部拆分开,谁需要使用,就调用即可。
建议:每个roles最好只使用一个tasks这样方便我们去调用,能够很好的做到解耦。(SOA)

roles目录结构(官方推荐样式)

# 商业转载请联系作者获得授权,非商业转载请注明出处。
# For commercial use, please contact the author for authorization. For non-commercial use, please indicate the source.
# 协议(License):署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)
# 作者(Author):曾志高翔(DriverZeng)
# 链接(URL):https://blog.driverzeng.com/driverzeng/6833.html
# 来源(Source):火鸡味锅巴

production                # inventory file for production servers
staging                   # inventory file for staging environment

group_vars/
   group1.yml             # here we assign variables to particular groups
   group2.yml
host_vars/
   hostname1.yml          # here we assign variables to particular systems
   hostname2.yml

library/                  # if any custom modules, put them here (optional)
module_utils/             # if any custom module_utils to support modules, put them here (optional)
filter_plugins/           # if any custom filter plugins, put them here (optional)

site.yml                  # master playbook
webservers.yml            # playbook for webserver tier
dbservers.yml             # playbook for dbserver tier

roles/
    common/               # this hierarchy represents a "role"
        tasks/            #
            main.yml      #  <-- tasks file can include smaller files if warranted
        handlers/         #
            main.yml      #  <-- handlers file
        templates/        #  <-- files for use with the template resource
            ntp.conf.j2   #  <------- templates end in .j2
        files/            #
            bar.txt       #  <-- files for use with the copy resource
            foo.sh        #  <-- script files for use with the script resource
        vars/             #
            main.yml      #  <-- variables associated with this role
        defaults/         #
            main.yml      #  <-- default lower priority variables for this role
        meta/             #
            main.yml      #  <-- role dependencies
        library/          # roles can also include custom modules
        module_utils/     # roles can also include custom module_utils
        lookup_plugins/   # or other types of plugins, like lookup in this case

    webtier/              # same kind of structure as "common" was above, done for the webtier role
    monitoring/           # ""
    fooapp/               # ""

image-20230529151714404

roles目录结构使用galaxy创建

[root@m01 ~]# cd /etc/ansible/roles/
[root@m01 roles]# tree wordpress/
nfs/                #项目名称
├── defaults        #低优先级变量
├── files           #存放文件
├── handlers        #触发器文件
├── meta            #依赖关系文件
├── tasks           #工作任务文件
├── templates       #jinja2模板文件
├── tests           #测试文件
└── vars            #变量文件

Ansible Roles依赖关系

roles允许你再使用roles时自动引入其他的roles。role依赖关系存储在roles目录中meta/main.yml文件中。
例如:推送wordpress并解压,前提条件,必须要安装nginx和php,把服务跑起来,才能运行wordpress的页面,此时我们就可以在wordpress的roles中定义依赖nginx和php的roles
[root@m01 roles]# vim /etc/ansible/roles/wordpress/meta/main.yml
dependencies:
  - { role: nginx }
  - { role: php }
#如果编写了meta目录下的main.yml文件,那么Ansible会自动先执行meta目录中main.yml文件中的dependencies文件,如上所示,就会先执行nginx和php的安装。

roles执行流程

image-20230529152106077

Ansible Roles最佳实践

#部署安装七层负载服务
# 任务
#base优化
[root@m01 roles]# cat /opt/ansible/roles/base
- name: 删除官方源
  archive:
    path: /etc/yum.repo.d/*
    dest: /tmp/yum.gz
    format: gz
    remove: true

- name: 更换阿里云
  copy:
    src: "{{ item.src }}"
    dest: "{{ item.dest }}"
  - with_items:
    - { src: /root/ansible/base/conf/Centos-7.repo,dest: /etc/yum.repo.d/Centos-Base.repo}
    - { src: /root/ansible/base/conf/epel-7.repo,dest: /etc/yum.repo/epel.repo }

 - name: 关闭防火墙
   service:
     name: firewalld
     state: stopped
     enabled: false

 - name: 关闭SeLinux
   selinux:
     state: disabled

 - name: 优化文件描述符
   pam_limits:
     domain: '*'
     limit_type: '-'
     limit_item: nofile
     value: '65535'

- name: 创建{{ user_group }}组
  group:
    name: {{ user_group }}
    gid: {{ id }}

- name: 创建{{ user }}用户
  user:
    name: {{ user_group }}
    uid: {{ id }}
    group: {{ id }}
    shell: /sbin/onlogin
    create_home: false
[root@m01 roles]# vim nginx/tasks/main.yml
---
# tasks file for zls-nginx
- name: 安装nginx
  yum:
    name: nginx
    state: present
- name: 推送主配置文件
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
  notify: Restart Nginx
- name: 启动nginx
  service:
    name: nginx
    state: started
    enabled: true
## 定义变量
[root@m01 vars]# vim /opt/ansible/roles/nginx/vars/main.yml
---
# vars file for nginx
user_group: 'root'
## 准备配置文件
[root@m01 roles]# ll nginx/templates/
total 4
-rw-r--r-- 1 root root 658 May 29 10:49 nginx.conf.j2
## 触发器
[root@m01 roles]# cat zlsnginx/handlers/main.yml
---
# handlers file for zls-nginx
- name: Restart Nginx
  service:
    name: nginx
    state: reloaded
# lb
## 依赖
[root@m01 roles]# cat lb/meta/main.yml
dependencies:
  - {role: zls-nginx}
## 任务
[root@m01 roles]# cat lb/tasks/main.yml
---
# tasks file for lb
- name: 推送负载均衡配置文件
  copy:
    src: lb.conf
    dest: /etc/nginx/conf.d
  notify: Restart Nginx
## 触发器
[root@m01 roles]# cat lb/handlers/main.yml
---
# handlers file for lb
- name: Restart Nginx
  service:
    name: nginx
    state: reloaded
## 配置文件
[root@m01 roles]# ll lb/files/lb.conf
-rw-r--r-- 1 root root 430 May 29 10:28 lb/files/lb.conf
# 入口文件
[root@m01 roles]# cat site.yml
- hosts: all
  roles:
  - {role: lb,when: ansible_hostname is match 'web*'}
## 执行入口文件
[root@m01 roles]# ansible-playbook site.yml

ansible galaxy使用

# 查询ansible代码仓库
[root@m01 ~]# ansible-galaxy search nginx
# 下载代码仓库中的代码
[root@m01 ~]# ansible-galaxy collection install aaronpederson.nginx

ansible vault

# 加密
[root@m01 ansible]# ansible-vault
encrypt site.yml
# 查看
[root@m01 ansible]# ansible-vault view
site.yml
# 编辑
[root@m01 ansible]# ansible-vault edit
site.yml
# 取消密码
[root@m01 ansible]# ansible-vault
decrypt site.yml
# 修改密码
[root@m01 ansible]# ansible-vault rekey
site.yml
0