官术网_书友最值得收藏!

  • Learning DevOps
  • Mikael Krief
  • 378字
  • 2021-06-24 12:32:12

Improving your playbooks with roles

Within an enterprise, when configuring a VM, we notice a certain repetition of tasks for each application, for example, several applications require the identical installation of nginx, which must be performed in the same way.

With Ansible, this repetition will require duplicating the playbook code, seen in our playbook example in the Writing a basic playbook section, between several playbooks (because each application contains its playbook). To avoid this duplication and, hence, save time, avoid errors, and homogenize installation and configuration actions, we can encapsulate the playbook code in a directory called role that can be used by several playbooks.

To create the nginx role corresponding to our example, we will create the following directory and file tree within our devopsansible directory:

Then, in the main.yml file, which is located in tasks, we will copy and paste the following code from our playbook in the file that is created:

- name: install and check nginx latest version
apt: name=nginx state=latest
- name: start nginx
service:
name: nginx
state: started

Then, we will modify our playbook to use this role with the following content:

---
- hosts: webserver
roles:
- nginx

Following the node roles, we provide a list of roles (names of the role directories) to be used. So, this nginx role is now centralized and can be used in several playbooks simply without having to rewrite its code.

The following is the code of a playbook that configures a VM web server with Apache and another VM that contains a MySQL database:

---
- hosts: webserver
roles:
- php
- apache
- hosts: database
roles:
- mysql
For more information on role creation, read the official documentation at  https://docs.ansible.com/ansible/latest/user_guide/playbooks_reuse_roles.html.

However, before we start creating a role, we can use Ansible Galaxy (https://galaxy.ansible.com/), which contains a large number of roles provided by the community and covers a high number of configuration and administration needs.

Within an enterprise, we can also create custom roles and publish them in a private galaxy within the company. More information can be found here: https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html.

In this section, we have detailed the writing of a playbook as well as its improvement with the use of roles. All of our artifacts are finally ready, so we will now be able to execute Ansible.

主站蜘蛛池模板: 奉化市| 曲沃县| 开平市| 建昌县| 社旗县| 三亚市| 肇源县| 大荔县| 连南| 射洪县| 弋阳县| 雅安市| 崇州市| 荔波县| 曲松县| 两当县| 遂平县| 疏勒县| 板桥市| 秦皇岛市| 辰溪县| 墨竹工卡县| 陆丰市| 贞丰县| 柳州市| 夏邑县| 阿拉善右旗| 磴口县| 石棉县| 左云县| 壤塘县| 上饶县| 凤城市| 夏河县| 大丰市| 景东| 夹江县| 岐山县| 南汇区| 拉萨市| 南川市|