CHAPTER 7 Ansible playbook(四)
创始人
2024-05-07 00:47:21
0

ansible-playbook

    • 7.1 roles(角色)
      • 7.1.1 Ansible Roles 介绍
      • 7.1.2 Roles结构
      • 7.1.3 存储和查找角色
      • 7.1.4 制作一个Role
      • 7.1.5 使用角色
        • 7.1.5.1 经典方法
        • 7.1.5.2 import_role
      • 7.1.6 如何使用Galaxy

7.1 roles(角色)

7.1.1 Ansible Roles 介绍

一个数据中心有可能存在好多类型的服务器。比如WEB类型、DB类型、开发人员使用的开发类型、QA使用的测试类型等等。如果每个类型的服务器的初始化行为都不一致,那要在一个PlayBook中将这些动作完成,这个PlayBook将变得臃肿、庞大,且难以后续维护和更新。如果能够针对每个类型的服务器单独编写PlayBook,最后通过某种方式整合这PlayBook, 在管理方式上就又会变得简单。

Ansible中提供了类似的概念,也就是Role。它允许管理员将他们复杂的PlayBook分解成一个个小的逻辑单元, 以便于维护和管理。

Roles是ansible自1.2版本引入的新特性,用于层次性,结构化地组织playbook,roles能够根据层次型结构自动自动装在变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令即可。简单来讲,roles就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中并可以便捷地include他们的一种机制,角色一般用于主机构建服务的场景中,但也可以是用于构建守护进程等场景中。

7.1.2 Roles结构

Role是什么?
从表面上看,它就是一个目录。目录的名字也就是role的名字叫做webservers。进到这个role名字的目录里,会发现好多子目录。

使用时,每个目录必须包含一个main.yml文件,这个文件应该包含如下目录名称对应的内容:

  • tasks: 存放 task 任务,包含角色要执行的任务的主要列表 ,tasks/main.yml -角色执行的主要任务列表,此文件可以使用 include包含其他的位于此目录中的tasks文件;
  • handlers: 存放 handlers 任务,包含处理程序,此角色甚至该角色之外的任何地方都可以使用这些处理程序
  • files: 存放 task 中引用的文件,包含可以通过此角色部署的文件
  • templages: 存放 task 中引用的模板
  • meta: 存在 role 的依赖role(这个role 执行前,要先执行那个role)
  • vars: 存放 role 的其他变量
  • defaults: 存在 role 的默认变量
  • library/my_module.py-模块,可以在该角色中使用
    角色必须至少包含这些目录之一,但是最好排除任何未使用的目录。
  1. tasks 文件夹中的 main.yml 文件
    - name: 安装 nginxyum: name=nginx state=present- name: 利用模板文件,设置主配置文件template:src: "{{ main_conf }}"dest: /etc/nginx/nginx.conftags: updatenotify: reload nginx server- name: check nginx syntaxshell: /usr/sbin/nginx -tregister: nginxsyntaxtags: update- name: 启动 nginx 服务when: nginxsyntax.rc == 0systemd: name=nginx state=started
  1. handlers 文件夹中的main.yml 文件
- name: reload nginx serverservice: name=nginx state=reloadedwhen: nginxsyntax.rc == 0
  1. files 文件夹存放文件
存放 default.conf 配置文件
  1. templates 文件夹存放模板
存放 nginx.conf.j2 模板
  1. vars 文件夹中的 main.yml 文件
main_conf: nginx.conf.j2
sub_conf: default.conf

7.1.3 存储和查找角色

默认情况下,Ansible在两个位置查找角色:

  • roles/相对于剧本文件位于名为的目录中
  • 在 /etc/ansible/roles

如果您将角色存储在其他位置,请设置role_path配置选项,以便Ansible可以找到您的角色。将共享角色检入一个位置可以使它们更容易在多个剧本中使用。有关在ansible.cfg中管理设置的详细信息,请参见配置Ansible。

[root@dbc-server-554 ansible]# cat /etc/ansible/ansible.cfg |grep roles_path
#roles_path    = /etc/ansible/roles

或者,您可以使用完全限定的路径来调用角色:

---
- hosts: webserversroles:- role: '/path/to/my/roles/common'或者
---
- hosts: webserversroles:- { role: '/path/to/my/roles/common' }

7.1.4 制作一个Role

最终优化的PlayBook

---
- name: task control playbook examplehosts: web_serversvars:createuser:- tomcat- www- mysqltasks:- name: create useruser: name={{ item }} state=presentwith_items: ""{{ createuser }}""- name: yum nginx webserveryum: name=nginx state=present- name: update nginx main configcopy: src=nginx.conf dest=/etc/nginx/tags: updatenotify: reload nginx server- name: check nginx syntaxshell: /usr/sbin/nginx -tregister: nginxsyntaxtags: update- name: check nginx runningstat: path=/var/lock/subsys/nginxregister: nginxrunningtags: update- name: print nginx syntaxdebug: var=nginxsyntax- name: start nginx serverservice: name=nginx state=startedwhen: nginxsyntax.rc == 0 and nginxrunning.stat.exists == falsehandlers:- name: reload nginx serverservice: name=nginx state=reloadedwhen: nginxsyntax.rc == 0 and nginxrunning.stat.exists == true

分解这个PlayBook,命名role的名字为nginx

[root@dbc-server-554 ansible]# mkdir nginx
[root@dbc-server-554 ansible]# cd nginx/
[root@dbc-server-554 nginx]# mkdir {file,handlers,tasks,templates,vars}
[root@dbc-server-554 nginx]# for d in `ls`;do
> touch ${d}/main.yml
> done
[root@dbc-server-554 nginx]# ls -R
.:
file  handlers  tasks  templates  vars./file:
main.yml./handlers:
main.yml./tasks:
main.yml./templates:
main.yml./vars:
main.yml

经过以上对PlayBook 的拆分,就形成了一个nginx 的 role。
回到本章开始的问题,当一个数据中心存在多种类型的服务器时,我们可以针对每个类型去单独写一个ROLE,这些ROLE 有可能分给不同的人去开发,这样不但使开发的逻辑变得简单,且开发效率也随着人员的增加而提升。

7.1.5 使用角色

可以通过三种方式使用角色:

  • 在播放级别具有以下roles选项:这是在播放中使用角色的经典方法。
  • 在任务级别上使用include_role:您可以在tasks播放区域的任何地方使用include_role。
  • 在任务级别上使用import_role:您可以在tasks剧本部分的任何位置静态重用角色import_role。

7.1.5.1 经典方法

使用角色的经典(原始)方法是roles给定播放的选项:

---
- hosts: serversroles:- foo- bar- foo

roles在播放级别使用该选项时,对于每个角色x

  • 如果存在role/x/tasks/main.yml,则Ansible将该文件中的任务添加到播放中。
  • 如果存在role/x/handlers/main.yml,则Ansible将该文件中的处理程序添加到播放中。
  • 如果存在role/x/vars/main.yml,则Ansible将该文件中的变量添加到播放中。
  • 如果存在role/x/defaults/main.yml,则Ansible将该文件中的变量添加到播放中。
  • 如果存在role/x/meta/main.yml,则Ansible将该文件中的所有角色依赖项添加到角色列表中。

在角色中,任何副本、脚本、模板或包含任务都可以引用role/x/{文件,模板,任务} /(目录取决于任务)中的文件,而不必相对或绝对地进行路径设置。

[root@dbc-server-554 ansible]# cat nginx.yml
---
- name: a playbook used rolehosts: allgather_facts: yesroles:- nginx[root@dbc-server-554 ansible]# ansible-playbook nginx.ymlPLAY [a playbook used role] ********************************************************************************************TASK [Gathering Facts] *************************************************************************************************
ok: [192.168.71.183]TASK [安装 nginx] ********************************************************************************************************
ok: [192.168.71.183]TASK [nginx : 利用模板文件,设置主配置文件] ******************************************************************************************
ok: [192.168.71.183]TASK [check nginx syntax] **********************************************************************************************
changed: [192.168.71.183]TASK [启动 nginx 服务] *****************************************************************************************************
ok: [192.168.71.183]PLAY RECAP *************************************************************************************************************
192.168.71.183             : ok=5    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

7.1.5.2 import_role

在playbook中给定 import_role 属性,必须放在tasks里面
这种方法适用于Ansible 2.4及以上

[root@dbc-server-554 ansible]# cat nginx2.yml
- name: a playbook used rolehosts: dbtasks:- debug:msg: "before we run our role"- import_role:name: nginx #角色名字- debug:msg: "after we ran out role"[root@dbc-server-554 ansible]# ansible-playbook nginx2.yml
#效果同上

7.1.6 如何使用Galaxy

Ansible的galaxy 工具,类似程序员使用的github。运维人员可以将自己编写的Role通过galaxy这个平台进行分享。同样,我们也可以通过galaxy 这个平台去获取一些我们想要的role。官网为:https://galaxy.ansible.com
网站

而ansible-galaxy 则是一个使用 galaxy 命令行的工具。它使我们不用访问galaxy 的网站而获取到需要的内容。

接下来我们将通过 ansible-galaxy 这个命令行去学习galaxy的使用。

[root@dbc-server-554 ansible]# ansible-galaxy --help
usage: ansible-galaxy [-h] [--version] [-v] TYPE ...Perform various Role and Collection related operations.positional arguments:TYPEcollection   Manage an Ansible Galaxy collection.role         Manage an Ansible Galaxy role.optional arguments:--version      show program's version number, config file location,configured module search path, module location, executablelocation and exit-h, --help     show this help message and exit-v, --verbose  verbose mode (-vvv for more, -vvvv to enable connectiondebugging)

在 ansible-galaxy 子命令 --help 中可以看到子指令
子指令包含: delete|import|info|init|install|list|login|remove|search|setup

ansible-galaxy delete|import|info|init|install|list|login|remove|search|setup --help	
[root@dbc-server-554 ansible]# ansible-galaxy role -h
usage: ansible-galaxy role [-h] ROLE_ACTION ...positional arguments:ROLE_ACTIONinit       Initialize new role with the base structure of a role.remove     Delete roles from roles_path.delete     Removes the role from Galaxy. It does not remove or alter theactual GitHub repository.list       Show the name and version of each role installed in theroles_path.search     Search the Galaxy database by tags, platforms, author andmultiple keywords.import     Import a rolesetup      Manage the integration between Galaxy and the given source.info       View more details about a specific role.install    Install role(s) from file(s), URL(s) or Ansible Galaxyoptional arguments:-h, --help   show this help message and exit
[root@dbc-server-554 ansible]# ansible-galaxy delete -h
usage: ansible-galaxy role delete [-h] [-s API_SERVER] [--api-key API_KEY][-c] [-v]github_user github_repopositional arguments:github_user           GitHub usernamegithub_repo           GitHub repositoryoptional arguments:-h, --help            show this help message and exit-s API_SERVER, --server API_SERVERThe Galaxy API server URL--api-key API_KEY     The Ansible Galaxy API key which can be found athttps://galaxy.ansible.com/me/preferences. You canalso set the token for the GALAXY_SERVER_LIST entry.-c, --ignore-certs    Ignore SSL certificate validation errors.-v, --verbose         verbose mode (-vvv for more, -vvvv to enableconnection debugging)

常用指令

// 在galaxy 上搜索共享的ROLE	
# ansible-galaxy search	
// 安装 galaxy 上共享的 ROLE	
# ansible-galaxy install	
// 列举已经通过 ansible-galaxy 工具安装的ROLE	
# ansible-galaxy list	
// 创建一个ROLE 的空目录架构, 这样我们在开发一个ROLE的时候,就不需要手动创建目录了。	
# ansible-galaxy init --offline

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...