第七章·自动化运维工具-Ansible roles

Ansible Roles基本概述

roles不管是Ansible还是saltstack,写一键部署的时候,都不可能把所有的步骤全部写入到一个'剧本'文件当中,我们肯定需要把不同的工作模块,拆分开来,解耦,那么说到解耦,我们就需要用到roles官方推荐,因为roles的目录结构层次更加清晰。

例如:我们之前推荐大家写一个base.yml里面写所有基础优化的项目,其实把所有东西摞进去也是很鸡肋的,不如我们把这些功能全部拆分开,谁需要使用,就调用即可。

建议:每个roles最好只使用一个tasks这样方便我们去调用,能够很好的做到解耦。(SOA)

Ansible Roles目录结构

官方推荐最佳实践目录结构定义方式

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/               # ""

2.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的安装。

Ansible Roles最佳实践

roles小技巧

  1. 创建roles目录结构,手动使用ansible-galaxy init test role
  2. 编写roles功能
  3. 在playbook中引用

使用roles重构rsync

1.规划目录结构如下

[root@m01 rsync]# cd /etc/ansible/roles/
[root@m01 roles]# ll
总用量 0
[root@m01 roles]# ansible-galaxy init rsync roles
- rsync was created successfully
[root@m01 roles]# tree
.
└── rsync
    ├── defaults
    │   └── main.yml
    ├── files
    ├── handlers
    │   └── main.yml
    ├── meta
    │   └── main.yml
    ├── README.md
    ├── tasks
    │   └── main.yml
    ├── templates
    ├── tests
    │   ├── inventory
    │   └── test.yml
    └── vars
        └── main.yml

2.定义roles主机清单

[root@m01 roles]# cat /etc/ansible/roles/hosts 
[backup]
172.16.1.41

3.指定backup主机组,执行哪个roles

[root@m01 roles]# cat /etc/ansible/roles/site.yml 
- hosts: all
  roles:
    - {role: rsync,when: ansible_hostname == 'backup'}

4.查看rsync角色的tasks任务

## 1.安装rsync
[root@m01 roles]# cat /etc/ansible/roles/rsync/tasks/install.yml
- name: Install Rsync
  yum:
    name: rsync

## 2.配置rsync
[root@m01 roles]# cat /etc/ansible/roles/rsync/tasks/config.yml
- name: Push Rsync Conf
  template:
    src: rsyncd.conf.j2
    dest: /etc/rsyncd.conf
  notify: restart rsync
- name: Create Passwd File
  copy:
    content: "{{ rsync_user }}:{{ rsync_passwd }}"
    dest: "{{ rsync_passwd_file }}"
    mode: 0600
- name: Create {{ backup_dir }}
  file:
    path: /{{ backup_dir }}
    state: directory
    owner: "{{ name }}"
    group: "{{ name }}"

## 3.启动rsync
[root@m01 roles]# cat /etc/ansible/roles/rsync/tasks/start.yml
- name: Start Rsync
  service:
    name: rsyncd
    state: started
    enabled: yes

## 4.将写完的task文件包含到main.yml中
[root@m01 roles]# cat /etc/ansible/roles/rsync/tasks/main.yml 
---
# tasks file for rsync
- include_tasks: install.yml
- include_tasks: config.yml
- include_tasks: start.yml

5.查看rsync角色的handlers

[root@m01 roles]# cat /etc/ansible/roles/rsync/handlers/main.yml 
- name: Restart Rsync Server
  service:
    name: rsyncd
    state: restarted

6.查看rsync角色的files目录

[root@m01 roles]#  ll /etc/ansible/roles/rsync/files/
total 8
-rw-r--r-- 1 root root 322 Nov 16 18:49 rsyncd.conf

7.查看rsync依赖

[root@m01 roles]# cat /etc/ansible/roles/rsync/meta/main.yml
dependencies:
  - {role: create_user}

  ## 此处省略编辑创建用户的playbook
  思路:1)初始化一个create_user目录
              2)在tasks/main.yml中写入创建用户和组即可
              3)建议使用变量

8.执行roles,使用-t指定执行测试rsync角色

[root@m01 roles]# ansible-playbook -i hosts  -t rsync site.yml 
PLAY [backup] ********************************************************************************************

TASK [Gathering Facts] ********************************************************************************
ok: [172.16.1.41]

TASK [backup : Install Rsync Server] ***********************************************************************
ok: [172.16.1.41]

TASK [backup : Configure Rsync Server] *********************************************************************
ok: [172.16.1.41]

TASK [backup : Start Rsync Server] *************************************************************************
ok: [172.16.1.41]

PLAY RECAP ********************************************************************************************
172.16.1.41                : ok=5    changed=0    unreachable=0    failed=0  

使用roles重构nfs

[root@m01 roles]# tree /etc/ansible/roles

├── group_vars
│   └── all
├── hosts
├── nfs
│   ├── files
│   ├── handlers
│   │   └── main.yml
│   ├── tasks
│   │   └── main.yml
│   ├── templates
│   │   └── exports
│   └── vars
├── site.yml

2.定义roles主机清单

[root@m01 roles]# cat /etc/ansible/roles/hosts 
[nfs]
172.16.1.31

3.指定nfs主机组,执行那个roles

[root@m01 roles]# cat /etc/ansible/roles/site.yml 
- hosts: nfs
  remote_user: root
  roles:
    - nfs
  tags: nfs

4.查看nfs角色的tasks任务

[root@m01 roles]# cat /etc/ansible/roles/nfs/tasks/main.yml 
- name: Install Nfs-Server
  yum:
    name:nfs-utils
    state: present

- name: Configure Nfs-Server
  template:
    src: exports
    dest: /etc/exports
  notify: Restart Nfs-Server

- name: Create Directory Data
  file:
    path: {{ share_dir }}
    state: directory
    owner: www
    group: www
    mode: 0755

- name: Start Nfs-Server
  systemd:
    name: nfs
    state: started
    enabled: yes

5.查看nfs角色的handlers

[root@m01 roles]# cat /etc/ansible/roles/nfs/handlers/main.yml 
- name: Restart Nfs-Server
  systemd:
    name: nfs
    state: restarted

6.查看rsync角色的files目录

[root@m01 roles]# cat /etc/ansible/roles/nfs/templates/exports 
{{ share_dir }} {{ share_ip }}(rw,sync,all_squash,anonuid=666,anongid=666)

7.nfs对应的变量定义

[root@m01 roles]# cat /etc/ansible/roles/group_vars/all 
#nfs
share_dir: /data
share_ip: 172.16.1.31

8.执行roles,使用-t指定执行nfs标签

[root@m01 roles]# ansible-playbook -i hosts  -t nfs site.yml 
PLAY [nfs] ********************************************************************************************

TASK [Gathering Facts] ********************************************************************************
ok: [172.16.1.31]

TASK [nfs : Install Nfs-Server] ***********************************************************************
ok: [172.16.1.31]

TASK [nfs : Configure Nfs-Server] *********************************************************************
ok: [172.16.1.31]

TASK [nfs : Create Directory Data] ********************************************************************
ok: [172.16.1.31]

TASK [nfs : Start Nfs-Server] *************************************************************************
ok: [172.16.1.31]

PLAY RECAP ********************************************************************************************
172.16.1.31                : ok=5    changed=0    unreachable=0    failed=0   

ansible Galaxy

Galaxy是一个免费网站,类似于github网站,网站上基本都是共享roles,从Galaxy下载roles是最快启动项目方式之一。

Galaxy官方网站:TP(https://galaxy.ansible.com/)

ansible提供了一个命令ansible-galaxy,可以用来对roles项目进行初始化,查找,安装,移除等操作

[root@m01 roles]# ansible-galaxy --help
Usage: ansible-galaxy [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...

Perform various Role related operations.

Options:
  -h, --help            show this help message and exit
  -c, --ignore-certs    Ignore SSL certificate validation errors.
  -s API_SERVER, --server=API_SERVER
                        The API server destination
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit
{1}
 See 'ansible-galaxy <command> --help' for more information on a specific
command.
{1}

使用galaxy搜索项目

[root@m01 roles]# ansible-galaxy search nginx

查看详细信息

[root@m01 ~]# ansible-galaxy info acandid.nginx

安装项目

[root@m01 ~]# ansible-galaxy install acandid.nginx

山林不向四季起誓 荣枯随缘