Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Ansible Roles and Best practic

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

Roles: put the playbook in their respective subdirectories according to their functions, such as handler,tasks, to form a collection, that is, roles.

The Roles directory can be the path defined by roles_path in ansible.cfg, or it can be stored in the same directory as the entry Playbook file. It is recommended to use roles_path to facilitate unified management. The example in this article is stored in the same directory as the entry Playbook file.

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.

Links to official documents:

Https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html

A simple official example on 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 relies on directory naming conventions and directory placement. The following is an official example that defines a directory structure for Roles:

Site.ymlwebservers.ymlfooservers.ymlroles/ common/ tasks/ handlers/ files/ templates/ vars/ defaults/ meta/ webservers/ tasks/ defaults/ meta/*.yml file: entry Playbook file site.yml: this name is generally the Playbook file name of the deployment project. If there are other tasks in the creation of Playbook, the name is arbitrary. Roles directory: the directory where Roles is stored. Each of the following subdirectories is a role, where there are common and webservers

Under each role, the directory is created on demand according to the function, and the directory name is standardized. There should be a main.yml file in each directory, which ansible will call.

The meaning of the directory name is as follows:

Tasks: define the task list of the role. You can use include to include other task files located in this directory: handlers: define the actions performed when triggering conditions in the role defaults: set the default variable with a very low priority. Basically, this value is used only when the variable has no value. Vars: define the variable used by the role, high priority files: used to store files called by the copy module or script module. No need for the main.yml file templates: used to store the jinjia2 template, the template module will automatically look for the jinjia2 template file in this directory. No need for main.yml file meta: defines metadata for roles, mainly for dependency multi-platform support

Officially, there is an example of multi-platform support that is differentiated in tasks.

There is also an example from the book that different platforms define different role names.

Finally, there is an example in the official best practice.

Tasks multi-platform support

Tasks level, corresponding to the tasks directory.

Define the role, and define multiple task files under the role. Judge the condition in main.yml and import the corresponding task file.

Tasks/main.yml is a must, as the entry file for tasks, but the actual code does not need to be written in this file, you can include other yaml files in this file. Officially there is an example of 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: presentroles multi-platform support

Role level, which corresponds to the role subdirectories under roles, such as common and webservers directories.

Define many roles directly and import all roles conditionally. Only roles that meet the requirements will be imported and executed.

Support multiple platforms at the roles level. Define unused roles in advance for different platforms. For example, the names of the two roles are httpd_db and httpd_rh. Then the Playbook file can be written as follows:

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

The way to judge the platform here should be the same as the one above, which is automatically judged by the host information obtained automatically by Ansible. The method of writing here is better than that of the official website above, low. I didn't have an actual test, so I kept the original way of writing.

Group_by module automatically groups hosts

Playbook level, which corresponds to the sibling directory of roles, such as the site.yml file.

First execute the task of a group_by module to dynamically group the hosts. Then set the playbook to the group separately.

This part of the content has nothing to do with roles, can be applied with roles, and can be applied without roles. It's an official best practice.

The group_by module can group hosts according to keywords. Keywords can be extracted from the host information, and after extraction, you can first splice a custom prefix or suffix. The resulting string becomes the group name of a host group, so that the hosts in Playbook can fill in the group name directly:

-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

Through the group_by module to dynamically add groups for the host, you can also create a group variable file in advance, these group variables will also take effect.

Using Roles

The official website has a variety of fancy skills:

Https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html#using-roles

Various fancy techniques:

Write role in tasks, which is a new syntax format. You can execute other task before and after the introduction of role while using absolute path to introduce role into role, and define variables to conditionally import role. This is how the multi-platform of roles above is used to tag roles. Using the scenario, I haven't figured out the role dependency yet.

With role dependency, you can automatically add other roles when you use a role. Role dependencies are defined under dependencies in the meta/main.yml file, which contains a list of dependent roles and dependent roles' parameters for the current character.

Example of a profile:

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

The role dependency is just a key in the meta file, that is, dependencies. Other key includes allow_duplicates, which defines that roles can perform tasks repeatedly. Other key does not appear in the document for the time being.

Embedded modules and plug-ins in roles

In the directory structure, the basic directory names used by the role are listed. The custom modules and plug-ins here are also placed in the role name subdirectory under the roles directory.

New directory structure:

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

A custom module has been added under the webservers role, and the directory name uses library.

There are many plug-ins for ansible. Here are two files with custom functions added to the filter plug-in under the webserver role.

Project directory structure

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

Production # inventory file for production environment stage # inventory file for commissioning environment group_vars/ # define group variable group1 group2host_vars/ # define host variable hostname1 hostname2library/ # if there is a custom module Put it here (optional) module_utils/ # if you have a tool to use in a custom module, put it here (optional) filter_plugins/ # if you have a custom filtering plug-in Put here (optional) site.yml # main playbookwebservers.yml # Web server playbookdbservers.yml # database server playbookroles/ # role file storage directory common/ # common role directory tasks/ # main.yml # Task entry handlers/ # main.yml # handler entry templates/ # Storage template Files ntp.conf.j2 # files/ # Storage File Resources bar.txt # foo.sh # vars/ # main.yml # define variables used by roles defaults/ # main.yml # define role default variables meta/ # main.yml # define role dependency webservers/ # webservers role directories Don't unfold.

The custom modules and plug-ins here are placed in the project directory and will not take effect automatically.

Default value of library: ~ / .ansible/plugins/modules:/usr/share/ansible/plugins/modules

Default value of filter_plugins: ~ / .ansible/plugins/filter:/usr/share/ansible/plugins/filter

You can find a lot of information about Ansible settings in this article of the official documentation, including the name of each variable in the configuration file, the name in the environment variable, and the default value of the variable.

Https://docs.ansible.com/ansible/latest/reference_appendices/config.html

You can modify the ansible.cfg configuration file, or you can create a soft connection using the location in the default home directory.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report