Ansible Roles and best practices

Role (roles): the playbook features, such as handler, tasks and other categories placed in separate subdirectories, formed in accordance with a set, is the role.
Roles in roles_path ansible.cfg directory can be defined path, and the inlet may be located in the same directory files Playbook. Recommended roles_path, convenient unified management. This example uses the entrance Playbook and files are stored in the same directory.

Roles are ways of automatically loading certain vars_files, tasks, and handlers based on a known file structure. Grouping content by roles also allows easy sharing of roles with other users.

Connection official document:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html

A simple example on the official GitHub:
https://github.com/ansible/ansible-examples

Official documentation of best practices:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html

Roles directory structure

Roles rely on directory naming and directory display. Here is an example of the official definition of the directory structure of a Roles:

site.yml
webservers.yml
fooservers.yml
roles/
    common/
        tasks/
        handlers/
        files/
        templates/
        vars/
        defaults/
        meta/
    webservers/
        tasks/
        defaults/
        meta/
  • * .Yml file: file entry Playbook
  • site.yml: The name is generally deployed Playbook file name of the project. If there are other tasks in the creation of Playbook, the name at random.
  • directory roles: Roles of storage directory. The following is a subdirectory for each character, there are common and webservers

In each role, create a directory function according to demand, there is a directory name specification. Under each directory should have a main.yml file, ansible This file is called.
Meaning of the name of the directory is as follows:

  • tasks: define the roles of the task list, you can use include contain other task files located in this directory
  • handlers: actions defined roles in the execution of the trigger condition
  • defaults: Set the default variable, low-priority, time is the basic value of the variable will not use this value
  • vars: variable defines the role of use, high priority
  • files: used to store the file copy module called by the script or module. Files do not need main.yml
  • templates: used to store jinjia2 template, template module will automatically find jinjia2 template files in this directory. Files do not need main.yml
  • meta: definition of the role of metadata is mainly used as a dependency

Multi-platform support

There is a distinction between official example of the tasks in a multi-platform support.
There is also an example of the different roles defined from the name of the book you see on different platforms.
Finally, one of the official best practice examples.

Multi-platform support tasks

level tasks, the corresponding tasks directory.
Defined the roles, defining multiple task files roles. A conditional judgment in the main.yml introduced corresponding task file.
tasks / main.yml must happen, as an entry document tasks, but do not write the actual code in this file, can contain other yaml files in this file. Official have an example of a multi-platform support:

# roles/example/tasks/main.yml
- import_tasks: redhat.yml
  when: ansible_facts['os_family']|lower == 'redhat'
- import_tasks: debian.yml
  when: ansible_facts['os_family']|lower == 'debian'

# roles/example/tasks/redhat.yml
- yum:
    name: "httpd"
    state: present

# roles/example/tasks/debian.yml
- apt:
    name: "apache2"
    state: present

Multi-platform support roles

Role level, the role of the corresponding subdirectory under roles, such as common directories and webservers.
Direct definition of a good number of roles, all the roles conditionally import. Only to meet the requirements of the role will be imported executed.
In the roles level to support multiple platforms. No pre-defined roles for different platforms. For example, two roles are httpd_db name and httpd_rh. Playbook file can then write:

# site.yml
- name: install httpd
  hosts: webservers
  roles:
    - { role: httpd_db, when: ansible_os_family == 'Deian' }
    - { role: httpd_rh, when: ansible_os_family == 'RedHat' }

Way above the platform where the judge should be the same, it is used to automatically determine the host information Ansible obtained automatically. Wording here is low than the wording of the above official website. I have not actually tested, it retains the original wording.

packet to the host module automatically group_by

playbook level, corresponding to the roles of the same directory, such as site.yml file.
A first task performing module group_by, dynamic grouping of hosts. After the groups are then set playbook.
This section and roles has nothing to do with the roles can be applied, useless roles can also apply. It is the best practice in official practice.
group_by host module may be grouped based on keywords. Keywords can be extracted from the host information, and then extracted, can be spliced on the first section of the custom prefix or suffix. The final string to get the group name will become a host group, such Playbook in the hosts can fill out the group name:

---
- name: talk to all hosts just so we can learn about them
  hosts: all
  tasks:
    - name: Classify hosts depending on their OS distribution
      group_by:
        key: os_{{ ansible_facts['distribution'] }}

# now just on the CentOS hosts...
- hosts: os_CentOS
  gather_facts: False
  tasks:
    - # tasks that only happen on CentOS go here

Dynamically add the host module by group_by grouping, you can create a good set of variables in advance file, these variables are also set to take effect in.

Using Roles

There are all kinds of fancy tricks official website:
https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html#using-roles

All kinds of fancy tricks:

  • The role written tasks, this is a new syntax. Other task can be performed before and after the introduction of role
  • Use an absolute path to introduce role
  • While the introduction of role, the definition of variables
  • Conditional import role, multi-platform above roles is so used
  • Add tags for the role. I did not want to understand usage scenarios

Role dependencies

By dependent roles, other characters may be automatically added when using roles. Roles define dependencies rely on meta / main.yml file, the content contains the current list of roles and role-dependent parameters dependent roles.
Configuration file example:

---
dependencies:
  - role: common
    vars:
      some_parameter: 3
  - role: apache
    vars:
      apache_port: 80
  - role: postgres
    vars:
      dbname: blarg
      other_parameter: 12

Dependencies role is just a key meta file, which is the dependencies. There are other key allow_duplicates, this is the definition of roles can repeat the task. Other key temporarily does not appear in the document.

Roles embedded modules and plug-ins

In the directory structure, the directory lists the basic use of the name of the role. Here custom modules and plugins subdirectory name is on the role of roles in the directory.
The new directory structure:

roles/
    webservers/
        tasks/
        defaults/
        meta/
        library/
            module1
            module2
        filter_plugins
            filter1
            filter2

In webservers role to add custom modules, directory name, use library.
There are many ansible plug-in webserver role here is to add two custom filter plug-in capabilities for files.

Project Directory Structure

Here is the official Ansible best practices recommended in a working directory structure:

production                # 生产环境的 inventory 文件
stage                     # 试运行环境的 inventory 文件

group_vars/               # 定义组变量
   group1
   group2
host_vars/                # 定义主机变量
   hostname1
   hostname2

library/                  # 如果有自定义的模块,放在这里(可选)
module_utils/             # 如果有自定义的模块中要使用的工具,放在这里(可选)
filter_plugins/           # 如果有自定义的过滤插件,放在这里(可选)

site.yml                  # 主 playbook
webservers.yml            # Web 服务器的 playbook
dbservers.yml             # 数据库服务器的 playbook

roles/                    # role 文件存放目录
    common/               # common 角色目录
        tasks/            #
            main.yml      #  task 入口
        handlers/         #
            main.yml      #  handler 入口
        templates/        #  存放模板文件
            ntp.conf.j2   #
        files/            #  存放文件资源
            bar.txt       #
            foo.sh        #
        vars/             #
            main.yml      #  定义角色使用的变量
        defaults/         #
            main.yml      #  定义角色默认变量
        meta/             #
            main.yml      #  定义角色依赖

    webservers/           # webservers 角色目录,不展开了

Here's custom modules and plug-ins are not automatically take effect in the project directory.
The default value of the library: ~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules
The default value of filter_plugins: ~/.ansible/plugins/filter:/usr/share/ansible/plugins/filter
This official document can be found in many defaults For related information Ansible settings, including the name of each variable in the configuration file, the name of the environment variable, and the variable .
https://docs.ansible.com/ansible/latest/reference_appendices/config.html

Ansible.cfg can modify the configuration file, you can also use the default location for the home directory, create a soft link.

Guess you like

Origin blog.51cto.com/steed/2436930